警告:首先是有问题的 JavaScript 代码!
// 1: buggy counter
// -----------------
// problem: 'this' can be "broken"
var Counter1 = function() {
this.count = 0;
this.increment = function() {
function increment_helper(){
++this.count; // this refers to window (global), not to the object that Counter1 was called with
}
increment_helper();
}
this.reset = function() { this.count = 0; }
this.get_count = function() { return this.count; }
}
var counter1 = new Counter1();
counter1.increment();
document.writeln("<p> 1: " + counter1.get_count() + "</p>");
可以看出,this
in increment_helper
而是指全局范围(或window
准确地说,如果我没弄错的话),而不是引用封闭闭包的 this 。这样,输出将是:
代替
1
我将列出更好的(仍然不完美,但还可以)解决方案,然后提出主要问题。因此,解决方案(恕我直言)可以这样整理:
// 2: better counter
// -----------------
// solved: 'that' can't be "broken"
var Counter2 = function() {
var that = this;
that.count = 0;
that.increment = function() {
function increment_helper(){
++that.count; // that refers right to the object the Counter1 was called with
}
increment_helper();
}
that.reset = function() { that.count = 0; }
that.get_count = function() { return that.count; }
}
var counter2 = new Counter2();
counter2.increment();
document.writeln("<p> 2: " + counter2.get_count() + "</p>");
所以,主要问题是:为什么this
JavaScript 中没有其他人那么特别吗?为什么只是this
目的是什么?
多谢!
Update:下面@Jordan 的评论(他解释了两者之间的区别)相对变量 like this
and 作用域变量像常规问题一样),重新表述我的问题:
A:相对变量背后的一般原理是什么?
B: why this
是 JavaScript 中唯一的相对变量吗?关于为什么相对/范围概念可以(排他地)应用于每个变量的任何理由?
答:在 JavaScript 中,与其他类似 C 的 OO 语言不同,函数是第一类对象。您可以复制函数、将它们传递到其他函数、从函数返回它们、创建新函数。功能有not就像 Java 或 C# 中永久附加到类声明中的方法一样。这意味着this
必须与函数本身及其调用方式相关。否则就没有意义。
举一个愚蠢的例子:
var o = {
name: "My name is o",
foo: function () { alert(this.name); }
};
var p = {
name: "My name is p",
};
p.foo = o.foo;
p.foo(); // "My name is p"
这在其他 OO C 类型语言中无法完成,但在 JavaScript 中可以。因此this
必须是相对的。是的,它会引起问题,但语言会变得难以置信用它表达。
B. arguments
也是相对的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)