简体   繁体   English

javascript object 文字和自执行函数

[英]javascript object literal and self-executing functions

I'm studying object literals and self-executing functions in Javascript.我正在研究 Javascript 中的 object 文字和自执行函数。 Looking through some YUI code I came across some methods of an object literal that execute themselves.通过一些 YUI 代码,我发现了一些可以自行执行的 object 文字的方法。 My question is why the following code does not alert 'Ohai Mark;';我的问题是为什么下面的代码没有提醒'Ohai Mark;';

var bar = {
    alert: function () {
        window.alert('Ohai Mark!');
    },
    init: (function () {
        bar.alert();
    }())
};

To explain in detail:详细解释:

> var bar = {

In javascript, declarations are processed first so bar exists as a variable before execution begins.在 javascript 中,首先处理声明,因此bar在执行开始之前作为变量存在。

>     alert: function () {
>         window.alert('Ohai Mark!');
>     },
>     init: (function () {
>         bar.alert();
>     }())

bar will be assigned a value after the expression on the right hand side is evaluated. bar将在评估右侧的表达式分配一个值。 During that evaluation, bar has whatever value it had when the statement (the entire line) was reached.在该评估期间, bar具有到达语句(整行)时的任何值。 It is currently undefined , and so it does not have an alert property yet.它当前是undefined ,因此它还没有alert属性。

> };

When executing the code, "bar" is defined but not yet assigned the resultant JSON object at the point which the init() method is defined (and about to assigned to the bar object) [EDITED] .执行代码时,“bar”已定义但尚未分配结果 JSON object 在定义 init() 方法的点(并且即将分配给bar对象) [EDITED] As init's function-scope is properly defined, I would declare the function there, like so:由于正确定义了 init 的函数范围,我将在那里声明 function,如下所示:

var bar = {
  init: (function () {
      var alert = function () {
        window.alert('Ohai Mark!');
      };

      alert(); //this will execute the code above
  }())
};

See Javascript Garden#namespaces and scopes .请参阅Javascript Garden#namespaces and scopes [EDIT] You might think this akin to: [编辑]你可能认为这类似于:

(function() {
  var c = c + 1;
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM