1

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) ?

asked Feb 5, 2013 at 15:23
2
  • 1
    In your first example, the function is a closure, it tries to access a variable called clicked. If it is not defined, you will get this error. Commented Feb 5, 2013 at 15:25
  • For one thing you should have a semicolong after the assignment = function () { [code] }**;** Commented Feb 5, 2013 at 15:26

1 Answer 1

4

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.

answered Feb 5, 2013 at 15:25
Sign up to request clarification or add additional context in comments.

2 Comments

But In JavaScript, scopes are declared by functions, and not by blocks. Can we talk about "objects scope" ?
@przemeko The "Object Scope" is a bit different; it's not considered it's own block, but essentially there is no clicked variable in any scope. It's this.clicked that's in whatever the current scope is.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.