[英]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()}
一句话,我对
handler.getName()
和function(){handler.getName()}
之间的区别感到困惑
For more detail,Please seet the code: 有关更多详细信息,请参见代码:
Jsfiddle checking url jsfiddle检查网址
My Question is : 我的问题是:
while I use obj.method ,the this can refer to handler and 虽然我使用obj.method , 但这可以引用处理程序和
while I use obj.method2 , the this refer to obj 当我使用obj.method2时 , 这是指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"
. 在第一种情况下,您直接调用处理程序对象的方法
getName
,在第二种情况中,您实际上将函数的浅表复制到了obj
对象中,因此在调用该函数时,它将运行相同的代码,但使用本地names
属性,因此您获得"obj"
。 If you would delete the names
in the obj
object, the value would be undefined. 如果要删除
obj
对象中的names
,则该值是不确定的。 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. 它与闭包无关,您只是将函数的内容复制到新的对象方法中,该函数中的
this
将引用新的宿主对象。
The difference in your code is not what you think it is. 您代码中的差异与您所想的不同。 In .method, you do this:
在.method中,您可以执行以下操作:
handler.getName()
In .method2 you do: 在.method2中,您可以执行以下操作:
handler.getName
If you change method2 to be: 如果将method2更改为:
handler.getName()
You will see that the results are the same for method and method2. 您将看到method和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() . 进入obj.method(), 这是指OBJ后(尝试handler.getName()。以前添加的声明文件撰写(this.names))之后的getName()调用处理程序 ,这样, 这指的是内部处理程序 handler.getName() 。
The function handler.getName was only assigned to obj.method2 , not yet called and this is not yet bound. 该功能handler.getName只分配给obj.method2,还没有叫, 这是没有约束。 When obj.method2() is called, then this is bound to obj inside method2() .
当obj.method2()被调用,那么这势必OBJ内部方法2()。
You can also try in the global scope: 您也可以在全局范围内尝试:
var f = handler.getName;
f(); // now window.names = "the window" is written
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.