2013-06-30 86 views
0

使用jsPlumb进行绑定,我将一个方法作为变量传递给回调函数。当它被调用时,“this”不是该方法所属的对象。我该如何去访问方法的对象实例,以便我可以访问它的变量和其他成员函数?javascript函数指针和“this”

我无法控制回调调用方法,它是一个单独的库。我所做的就是从我的对象init方法调用绑定。我希望this在我的_connection方法里成为它的对象。

jsPlumb.bind('connection', this._connection); 
+3

真的下来票呢? – Justin808

回答

1

this任何function的值是determined when it's calledfunction确实与“对象”没有任何联系,而不管它是否被称为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)); 
+0

但是,'.bind()'的第一个参数应该是你希望'this'指针所在的对象本身,而不是像你和OP那样的字符串''connection''。我不明白你是如何用你的代码解决任何问题的。 – jfriend00

+0

@ jfriend00我认为'jsPlumb.bind()'是一个事件处理函数而不是函数上下文,''connection''是事件名称。 –

+0

我想这个问题很难说清楚。 – jfriend00

1

如果您不想使用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:");