这是一个合法的JavaScript语法吗?

时间:2014-12-02 10:14:53

标签: javascript function syntax

我想询问是否正确声明了以下函数,以及是否可以使用此语法。

(function(){



$(document).on("click", ".MyButton", function(event)
{
    if ($(this).attr("id") == "ButtonAuftrag")
    {
        $.mobile.changePage("#pagetwo");

    }
}
)();

单击按钮时应触发该功能。我google了,从来没有找到这样的语法。 第一行(function(){和关闭函数让我感到困惑。

4 个答案:

答案 0 :(得分:1)

很少有事情可以照顾

(function() {//<-- its function without name
  $(document).on("click", ".MyButton", function(event) {
    if (this.id === "ButtonAuftrag") {//<-- updated this line
      $.mobile.changePage("#pagetwo");
    }
  });//<-- added this line
})();//<-- executing the block declared
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

示例示例,名称为:

var run = function() { //<-- named as `run`
  console.log('running...');
}; //<-- not invoked

console.log('after run() declared ...');
run(); //<-- invoked
console.log('run() executed ...');
open console... F12

示例示例,没有名称:

(function() {
  console.log('runner 1 ...');
}); //<-- not invoked

console.log('after runner 1 declared ...');

(function() {
  console.log('runner 2 ...');
})(); //<-- invoked

console.log('after runner 2 declared ...');

(function(x) {
  console.log('runner 3 ...', 'x: ', x);
})(56); //<-- invoked with parameters

console.log('after runner 3 declared ...');
open console... F12

答案 1 :(得分:0)

这称为自调用匿名函数或IIFE (Immediately Invoked Function Expression)

虽然有一些轻微的语法问题,但我会将错误的副本粘贴到网站中。请参阅解决此问题的其他答案。

基本上,这里发生的是你将整个函数定义为括在括号中的表达式;与表达式类似:

var a = ( 3 == 5 )

这将使用值false填充变量a。以类似的方式,在用括号括起函数之后,该函数实际上被称为()。所以基本上这个函数一旦被定义就被调用。

答案 2 :(得分:0)

http://en.wikipedia.org/wiki/Immediately-invoked_function_expression

预先修正一些错误

(function(){

  $(document).on("click", ".MyButton", function() { // You don't use any event
    if ( this.id == "ButtonAuftrag"){ // Use this force Luke
        $.mobile.changePage("#pagetwo");
    }
  }); // Close properly

}()); // Close properly

fiddle

它被称为 IIFE 立即调用函数表达式

(function(){
      // Function Scope's Code here...
      // Declared variables become private and
      // not accessible from outside the fn scope
}()); // the () here will expose to execution the function content

简单示例:

(function(){
   console.log("HEYYY");
   a = "a";     // Global variable (in window Object)
}());           // "HEYYY" 
console.log(a); // "a" // accessible


(function(){
  console.log("HEYYY");
  var b = "b";  // Private variable 
}());            
console.log(b); // referenceError : b is not defined

答案 3 :(得分:-1)

不,你没有关闭外部功能。你想要这个吗?

(function(){
    $(document).on("click", ".MyButton", function(event) {
        if ($(this).attr("id") == "ButtonAuftrag"){
            $.mobile.changePage("#pagetwo");
        }
    })
}());