[英]How to access instance property in an instance method when the method is being passed into an another function?
I know in the code below it will print out undefined
if I click on the button, because this.field
becomes within the context of the button and not Container
. 我知道在下面的代码中,如果单击按钮,它将打印出
undefined
,因为this.field
变为按钮的上下文而不是Container
。 My question is how can I access this.field
of Container
when this.func
is passed into another function, which is a different context scope than Container
. 我的问题是如何访问
this.field
的Container
时this.func
传递到另一个函数,这比一个不同的上下文范围Container
。
function Container(){
this.field = 'field';
$('button').click(this.func);
}
Container.prototype.func = function(){
console.log(this.field);
}
I know I can do this, but is there a better way? 我知道我可以做到这一点,但有更好的方法吗? Because I'd rather define the methods outside the constructor so I won't clutter it.
因为我宁愿在构造函数之外定义方法,所以我不会混淆它。
function Container(){
var thisObj = this;
this.field = 'field';
$('button').click(function(){ console.log(thisObj.field) });
}
How about passing an anonymous function? 传递一个匿名函数怎么样?
function Container(){
this.field = 'field';
var self = this;
$('button').click(function() {
self.func()
});
}
You have not many choices here... 你在这里没有多少选择......
jQuery makes it a bit easier for you and offers $.proxy
: jQuery让你更容易,并提供
$.proxy
:
$('button').click($.proxy(this.func, this));
// or
$('button').click($.proxy(this, 'func'));
Pass the object reference in as the event data: 将对象引用作为事件数据传递:
function Container(){
this.field = 'field';
$('button').click(this, this.func);
}
Container.prototype.func = function(e){
console.log(e.data.field);
}
See here: http://jsfiddle.net/gilly3/nwtqJ/ 见这里: http : //jsfiddle.net/gilly3/nwtqJ/
I'd just like to point out that, generally speaking, you should avoid thinking of the 'this' variable as having any resemblance to the one in java. 我只想指出,一般来说,你应该避免将'this'变量视为与java中的变量有任何相似之处。 You clearly understand that, but it always bears repeating.
你清楚地了解这一点,但它总是重复。 Since javascript's this always points to the object on which you called the function, your passing of an instance function to another object to use as its onclick leads to confusion.
由于javascript总是指向您调用该函数的对象,因此将实例函数传递给另一个对象以用作其onclick会导致混淆。 I don't know what you intend to do in the instance method itself, but there is no reason why an onclick handler should be an instance method of another object.
我不知道你打算在实例方法本身做什么,但是没有理由为什么onclick处理程序应该是另一个对象的实例方法。 If it's access to the members you want, they're public, so no need to have it be an instance method.
如果它可以访问您想要的成员,那么它们是公共的,因此不需要将它作为实例方法。 If the work to be done relates exclusively to the Container object, then the onclick should possibly be a separate function that would have a refernce to the container and call the instance method.
如果要完成的工作仅与Container对象相关,则onclick应该是一个单独的函数,它将引用容器并调用实例方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.