方法调用模式vs函数调用模式



阅读JavaScript Good Parts,我遇到两种调用函数的模式:

//方法调用

var myObject = {
    value: 0;
    increment: function (inc) {
        this.value += typeof inc === 'number' ? inc : 1;
    }
};
myObject.increment(  );
document.writeln(myObject.value);    // 1
myObject.increment(2);
document.writeln(myObject.value);    // 3

//函数调用

myObject.double = function (  ) {
    var that = this;    // Workaround.
    var helper = function (  ) {
        that.value = add(that.value, that.value)
    };
    helper(  );    // Invoke helper as a function.
};
// Invoke double as a method.
myObject.double(  );
document.writeln(myObject.getValue(  ));    // 6

方法调用模式是有意义的。然而,在函数调用模式中,他说"当函数不是对象的属性时,它就被作为函数调用"。等等,double函数不是myObject的属性吗?我假设这里myObject是一个对象字面量,尽管它没有在文本中显示其初始化。因此,如果它是对象字面量,那么这两种模式之间就没有区别。我们所做的就是将一个值增加到字面量。此外,有人知道这个getValue()是从哪里来的吗?

我知道这两者在某种程度上确实不同,因为this在函数调用中指的是函数调用中的全局上下文,而它在方法调用模式中指的是对象本身。

区别在于this关键字在函数中的工作方式。奇怪的有趣的是,在JavaScript中,它并不取决于函数是如何定义的,而是取决于它是如何调用的:

如果函数调用为helper(),则不能在helper代码中使用this(具有有意义的值)

如果函数作为myObject.double()调用,我们称之为"方法调用",double代码中的this如预期的那样是myObject

书中的这个例子出于某种原因让我很困惑。我重新设计了他的例子,以更好地匹配他的解释(IMHO)

var myObject = {
    value: 1,
    double: function() {
        that = this;
        var inner = function() { that.value = that.value + that.value; };
        inner();     // Functional invocation
    }
};
myObject.double();  // Method invocation
console.log(myObject.value);

方法模式

方法是使用方法模式调用的,因此this绑定到myObject

<<p> 功能模式/strong>

内部方法是使用函数模式调用的,因此this绑定到全局对象而不是myObject

请注意,如果按以下方式修改double方法,则对value属性没有影响:

double: function() {
    var inner = function() { this.value = this.value + this.value; };
    inner();
 }

最新更新