开发者

confusion over `this` keyword

开发者 https://www.devze.com 2023-03-24 21:37 出处:网络
I\'m reading crockford\'s Javascript: The Good Parts and am messing around with this piece of code from the lesson invocation patterns:

I'm reading crockford's Javascript: The Good Parts and am messing around with this piece of code from the lesson invocation patterns:

var br = "<br />";

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

var myObject = {
    value: 0,
    increment: function(inc) {
        this.value += typ开发者_如何学Pythoneof 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

After the double method is called, I'm getting undefined. Does anyone know why?


Your "add()" function is missing a return statement:

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

A function without a return statement actually "returns" undefined.


I think you should return the result in the add function:

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

精彩评论

暂无评论...
验证码 换一张
取 消