关于`this`关键字的混淆

时间:2011-08-03 23:02:28

标签: javascript oop this

我正在阅读crockford的Javascript:The Good Parts,并且正在讨论课程调用模式中的这段代码:

var br = "<br />";

var add = function(a,b) {
    a + b;
}

var myObject = {
    value: 0,
    increment: function(inc) {
        this.value += typeof inc === "number" ? inc : 1;
    }
};

myObject.increment(2);
document.write(myObject.value + br);    // 2

myObject.increment();
document.write(myObject.value + br);    // 3

myObject.increment(3);
document.write(myObject.value + br);    // 5

myObject.double = function() {
    var that = this;

    var helper = function() {
        that.value = add(that.value,that.value);
            return that.value;
    };

    helper();
};

myObject.double();
document.write(myObject.value);     //undefined

调用double方法后,我收到undefined。有谁知道为什么?

2 个答案:

答案 0 :(得分:10)

您的“add()”函数缺少return语句:

var add = function(a,b) {
  return a + b;
}

实际上没有return语句的函数"returns" undefined

答案 1 :(得分:5)

我认为你应该在add函数中返回结果:

var add = function(a,b) {
    return a + b;
}
相关问题