使用jsPlumb进行绑定,我将一个方法作为变量传递给回调函数。当它被调用时,“this”不是该方法所属的对象。我该如何去访问方法的对象实例,以便我可以访问它的变量和其他成员函数?javascript函数指针和“this”
我无法控制回调调用方法,它是一个单独的库。我所做的就是从我的对象init方法调用绑定。我希望this
在我的_connection
方法里成为它的对象。
jsPlumb.bind('connection', this._connection);
使用jsPlumb进行绑定,我将一个方法作为变量传递给回调函数。当它被调用时,“this”不是该方法所属的对象。我该如何去访问方法的对象实例,以便我可以访问它的变量和其他成员函数?javascript函数指针和“this”
我无法控制回调调用方法,它是一个单独的库。我所做的就是从我的对象init方法调用绑定。我希望this
在我的_connection
方法里成为它的对象。
jsPlumb.bind('connection', this._connection);
的this
任何function
的值是determined when it's called。 function
确实与“对象”没有任何联系,而不管它是否被称为object.method()
或method.call(object)
。
因此,通过一个function
具有固定this
值,它会需要是bound:
jsPlumb.bind('connection', this._connection.bind(this));
jQuery的还包括包装和兼容性填补这个与jQuery.proxy()
:
jsPlumb.bind('connection', $.proxy(this._connection, this));
如果您不想使用Function.prototype.bind(因为它在旧版浏览器中不受支持),并且您不想使用jquery,则可以使用更复杂的版本:
jsPlumb.bind('connection', (function(me){
return function(){
me._connection();// no need for call, apply or bind
}
})(this));
失去this
传递对象的方法时,一个常见的问题,现在的问题是,它是在脚本生成解决方案重新:
var ps={//publish subscribe
messages:{},
add:function(m,fn){
if(!this.messages[m]){
this.messages[m]=[];
}
this.messages[m].push(fn);
},
publish:function(m,data){
var i = 0;
var msg=this.messages[m];
for(i=0;i<msg.length;i++){
msg[i](data);
}
}
}
function test(){
}
test.prototype.logit=function(data){
console.log(data,this.toString());
};
test.prototype.toString=function(){
return "This is a test object";
}
// self made bind function
function myBind(me,fn){
return function(){
fn.apply(me,arguments);
}
}
var t=new test();
// pass a closure instead of a function
ps.add("test1",(function(me){
return function(data){
me.logit(data);
}
})(t)
);
// pass a function
ps.add("test2",t.logit);
// function created with bind
ps.add("test3",t.logit.bind(t));
// passing closure using myBind
ps.add("test4",myBind(t,t.logit));
// next line will log "This is a test object"
ps.publish("test1","Passing a closure instead of the function, this is:");
// next line will log "function (data){console.log(..."
// so `this` is not test but test.logit
ps.publish("test2","Passing a the function, this is:");
// next line will log "This is a test object"
ps.publish("test3","Passing a the function using bind, this is:");
// next line will log "This is a test object"
ps.publish("test4","Passing a closure with myBind, this is:");
真的下来票呢? – Justin808