dopatraman
dopatraman

Reputation: 13908

confusion over `this` keyword

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 += 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

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

Upvotes: 0

Views: 152

Answers (2)

Pointy
Pointy

Reputation: 413702

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.

Upvotes: 10

Cem Kalyoncu
Cem Kalyoncu

Reputation: 14593

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

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

Upvotes: 5

Related Questions