1

我掌握了基本的 javascript 语法,并且正在努力更深入地理解该语言。我正在查看elizabot.jselizabot.js 库中文件中的这行代码:

var global=ElizaBot.prototype.global=self;
  1. 我认为这是将 Elizabot 对象原型的全局属性设置为“self”。我是否正确理解该行的含义?
  2. Self 似乎不是 javascript 中的保留字。但是,如果我在 Elizabot.js 文件中搜索“self”这个词,我找不到它。javascript中的self这个词有什么特殊含义吗?我找不到声明。
4

2 回答 2

4

In the browser, self refers to the global window object

ElizaBot is a function that is setting its global property to the window object for all instances of ElizaBot created (through prototype)

var global = ElizaBot.prototype.global=self;
function ElizaBot(){
  console.warn(this.global == self);
  console.warn(this.global == window);
  console.warn(self == window);
  console.warn(self.self.self.window.self == this.global.self.window);
  // I can go on forever :) time to stop
}
new ElizaBot();
new ElizaBot();
于 2013-09-26T21:07:50.873 回答
2

In a browser (not in generic javascript), self is a property of the window object that contains the value of the current window. Since all properties of the window object are accessible as global variables, you can refer to just self and it will contain a reference to the current document's window.

Thus, in your code:

var global=ElizaBot.prototype.global=self;

is assigning to both ElizaBot.prototype.global and to the variable global a reference to the current window object.

See here for info on window.self which is also accessible as just self.


FYI, all of these assignments seem superfluous since the current window object is generally accessible in other ways and need not be stored separately.

于 2013-09-26T21:07:29.303 回答