为什么'这个'解决方案在JavaScript中如此特别?

Bre*_*eak 5 javascript programming-languages functional-programming

警告:首先是Buggy 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>");
Run Code Online (Sandbox Code Playgroud)

可以看出,thisin increment_helper而不是指全局范围(或​​者window范围是精确的,如果我做对了),而不是引用封闭闭包的这个.这样,输出将是:

0

代替

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>");
Run Code Online (Sandbox Code Playgroud)

所以,主要的问题是:为什么this像JavaScript中的其他人一样特殊?为什么它只是this为了什么目的?

非常感谢!

更新:继以下@乔丹的意见(他解释之间的差异相对变量this范围变量像普通的),改写我的问题:

答:相对变量背后的一般原理是什么?

B:为什么thisJavaScript中唯一的相对变量?关于为什么相对/范围概念可以(专门)应用于每个变量的任何理由?

jmb*_*all 2

答:在 JavaScript 中,与其他类似 C 的 OO 语言不同,函数是第一类对象。您可以复制函数、将它们传递到其他函数、从函数返回它们、创建新函数。函数不像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"
Run Code Online (Sandbox Code Playgroud)

这在其他 OO C 类型语言中无法完成,但在 JavaScript 中可以。因此this必须是相对的。是的,它会引起问题,但语言因此变得非常具有表现力。

B.arguments也是相对的。