przemeko
przemeko

Reputation: 39

Closures in functions and objects

Snippets below do exactly the same. First one:

var obj_button = {
    clicked: 1,
    click: function() {
        console.log(clicked);
    }
};

Second one:

var Func_button = function() {
    var clicked = 1;
    this.click = function() {
        console.log(clicked);
    }
}

But when i want to make use of closures, the first approach fails:

func = new Func_button();
func.click(); // OK - works fine, outputs 1
obj_button.click(); // FAIL - he don't know what is "clicked"

So my question is: why in first approach, method click() has no ability to see "clicked" param. Shouldn't closure cover this param (just like in second example) ?

Upvotes: 1

Views: 49

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

No, because clicked in the first instance is in the object scope while in the second instance it is in the function scope. this.click = function is also within the function scope, but the contents of click: function () { are in a different scope.

For the first example to work, you can use:

console.log(this.clicked);

You can also see the same behavior if you rewrite your second example:

var Func_button = function() {
    this.clicked = 1;
    this.click = function() {
        console.log(clicked);
    };
}

Now, func.clicked will return 1, but calling func.click() will result in the same error.

Upvotes: 4

Related Questions