关于`this`关键字的混淆

dop*_*man 1 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
Run Code Online (Sandbox Code Playgroud)

double调用该方法后,我就到了undefined.有谁知道为什么?

Poi*_*nty 10

你的"add()"函数缺少一个return语句:

var add = function(a,b) {
  return a + b;
}
Run Code Online (Sandbox Code Playgroud)

没有return语句的函数实际上"返回"未定义.


Cem*_*ncu 5

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

var add = function(a,b) {
    return a + b;
}
Run Code Online (Sandbox Code Playgroud)