question about closure in javascript with an example
there
In a word,I'm confused about the difference between
handler.getName()
and
function(){handler.getName()}
For more detail开发者_如何学C,Please seet the code:
Jsfiddle checking url My Question is : while I use obj.method ,the this can refer to handler and while I use obj.method2, the this refer to obj I know this is something about closure,But I just don't know how to explain such things Hope someone can help,Thanks a lot!In the first case you are calling directly the method getName
of the handler object, in the second one, you practically did a shallow copy of the function into the obj
object, so when you call it will run the same code but use the local names
attribute, so you get "obj"
. If you would delete the names
in the obj
object, the value would be undefined. It has nothing to do with closures, you just copied the contents of a function into a new object method, and the this
in that function will refer to the new host object.
The difference in your code is not what you think it is. In .method, you do this:
handler.getName()
In .method2 you do:
handler.getName
If you change method2 to be:
handler.getName()
You will see that the results are the same for method and method2.
If a function is called as a method on an object then this refers to the object:
var x = {
a: 1,
f: function() {return this.a;}
};
document.write(x.f()); // writes 1
After entering obj.method(), this refers to obj (try to add the statement document.write(this.names) before handler.getName().) Then getName() is called on handler, such that this refers to handler inside handler.getName().
The function handler.getName was only assigned to obj.method2, not yet called and this is not yet bound. When obj.method2() is called, then this is bound to obj inside method2().
You can also try in the global scope:
var f = handler.getName;
f(); // now window.names = "the window" is written
精彩评论