javascript,函数与变量

Zac*_*ith 10 javascript

我开始研究Javascript和JQuery(因此我选择下面的例子).我发现我可以定义一个函数并调用它(如预期的那样),但我也可以......还做其他事情 ......这就是问题所在:

function $() {
    console.log('hi');
}

$()
$
Run Code Online (Sandbox Code Playgroud)

我没有使用函数调用或只是在不调用函数的情况下声明'$'.后者到底在做什么?如果它实际上没有调用函数,为什么它可以工作?

SLa*_*aks 10

它什么都不做.它只是一个碰巧持有函数的变量.

它与以下同样无用的代码没有什么不同:

42;
Run Code Online (Sandbox Code Playgroud)

  • 42,嗯?我看到你在那里做了什么. (3认同)

Raú*_*tín 3

JavaScript 对象是键和值之间的映射。键是字符串,值可以是任何内容。这使得对象自然适合哈希图。

函数是具有可调用附加功能的常规对象。

来自 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structs#.22Normal.22_objects.2C_and_functions

这意味着您可以执行以下操作:

function test(){
   console.log(1);
}

var a = test;

a();
Run Code Online (Sandbox Code Playgroud)

或者

var test2 = function(){
  console.log(2);
}
Run Code Online (Sandbox Code Playgroud)

或自动呼叫

//sorry for the indentation.
(
  function(){
     console.log(3);
  }
)()
Run Code Online (Sandbox Code Playgroud)

或者创建结构

var testHash = {
   a : 1,
   b : function(){
      console.log(4);
   }
}

testHash.b();

testHash['b']();
Run Code Online (Sandbox Code Playgroud)

并创建难以调用的函数:

//in a browser environment
window['test3'] = function(){
   console.log(5);
} 

window['test space'] = function(){
   console.log(6);
} 

test3() //no error
test space() //error :D
Run Code Online (Sandbox Code Playgroud)

编辑:用户想了解更多有关自动调用功能的信息:

为什么要做这个工作?

(
  function(){
     console.log(3);
  }
)()
Run Code Online (Sandbox Code Playgroud)

只需两步即可轻松完成:

括号,如果我们知道一个函数就像其他变量一样,并且我们知道括号仅用于创建组或调用函数。

var test_1 = 'string example';
var length = (test_1).length; // the same that test_1.length
Run Code Online (Sandbox Code Playgroud)

有意义的是:

var test_1 = 'string';
var test_2 = ' example';
var length = (test_1 + test_2).length; // the same that test_1.length
Run Code Online (Sandbox Code Playgroud)

代替:

var test_1 = 'string';
var test_2 = ' example';
var aux = test_1 + test_2;
var length = aux.length; // the same that test_1.length
Run Code Online (Sandbox Code Playgroud)

现在,这对您有意义吗?:

var length = ('string example').length; // instead the first example
Run Code Online (Sandbox Code Playgroud)

第二步,我们可以更改函数的字符串..并调用它

( function(){ ... } )()
Run Code Online (Sandbox Code Playgroud)

为什么这很有趣?好了,现在出现了闭包的概念。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

闭包是 javascript 中非常重要的工具。