我怎样才能在obj的处理函数中得到变量?没有参考MyClass中的obj.
var obj = {
func: function(){
var myClass = new MyClass();
myClass.handler = this.handler;
myClass.play();
},handler: function(){
//Here i don't have access to obj
console.log(this); //MyClass
console.log(this.variable); //undefined
},variable:true
};
function MyClass(){
this.play = function(){
this.handler();
};
this.handler = function(){};
};
obj.func();
如果您使用Base.js或其他类似的oop方式,那么构建需要您.
_.bindAll(obj)(下划线metod)也不合适.它在Base.js中突破了.
最佳答案
仅绑定处理程序方法:http://jsfiddle.net/uZN3e/1/
原文链接:https://www.f2er.com/js/429557.htmlvar obj = {
variable:true,func: function(){
var myClass = new MyClass();
// notice Function.bind call here
// you can use _.bind instead to make it compatible with legacy browsers
myClass.handler = this.handler.bind(this);
myClass.play();
},handler: function(){
console.log(this.variable);
}
};
function MyClass(){
this.play = function(){
this.handler();
};
this.handler = function(){};
};
obj.func();