我知道 self 这个词在 javascript 中没有特殊含义。在代码下方,虽然如果写成 var Life = function( ....),很明显但是作者决定做 var _ = self.Life = function(...)。虽然我理解 var _ 部分(因此在内部,它可以通过更短的名称来指代相同的东西),但我没有得到 self.Life(而不是 Life)。有人可以解释一下吗?
(function() {
var _ = self.Life = function(seed) {
this.seed = seed;
this.height = seed.length;
this.width = seed[0].length;
this.prevBoard = [];
this.board = cloneArray(seed);
};
_.prototype = {
next: function() {
//
},
toString: function() {
return this.board.map(function(row) {
return row.join(' ');
}).join('\n');
}
};
function cloneArray(array) {
return array.slice().map(function(row) {
return row.slice();
});
}
})();
undefined
var game = new Life([
[0, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 1]
]);
undefined
console.log(game + ' ');
最佳答案
I understand the word
self
has no special meaning in javascript.
不,但它是一个 predefined global on browsers ,指的是当前窗口(就像 window
那样*)。所以
var _ = self.Life = function...
...正在使 Life
成为全局性的,而不会成为 The Horror of Implicit Globals 的牺牲品**.
简单的例子:
(function() {
var _ = self.Life = function() {
console.log("Hi there");
};
new _();
})();
new Life();
* window
和 self
过去对当前窗口的引用略有不同,但在现代浏览器中,window === self
是true
为 window
和 self
的默认值。
** (这是我贫血的小博客上的帖子)
关于javascript做新的不同的名字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46131011/