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

时间:2014-08-16 19:52:11

标签: javascript

阅读 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

方法调用模式很有意义。但是,在函数调用模式中,他说“当一个函数不是一个对象的属性时,它就作为一个函数被调用”。那么等一下,是不是myObject属性的双重功能?我假设myObject是一个对象文字虽然它没有在文本中显示它的初始化。因此,如果它是一个对象文字,那么这两个模式之间没有区别。我们所做的只是增加文字的值。此外,有谁知道这个getValue()来自哪里?

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

2 个答案:

答案 0 :(得分:0)

区别在于this keyword在函数内部的工作方式。 奇怪有趣的是,在JavaScript中,它不依赖于函数的定义方式,而是如何调用函数:

如果该函数被调用为helper(),则您无法在this代码中使用helper(带有意义的值)。

如果该函数被称为myObject.double(),我们称之为“方法调用”,this代码中的double符合预期的myObject

答案 1 :(得分:0)

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

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);

方法模式

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

功能模式

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

如果您修改 double 方法,请注意value属性没有影响,如下所示:

double: function() {
    var inner = function() { this.value = this.value + this.value; };
    inner();
 }
相关问题