javascript函数指针和“this”

时间:2013-06-30 04:11:00

标签: javascript jquery jsplumb

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

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

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

2 个答案:

答案 0 :(得分:1)

任何this的{​​{1}}值为determined when it's calledfunction与“对象”实际上没有任何联系,而不是它是function还是object.method()

因此,要传递具有固定method.call(object)值的function,它必须为bound

this

jQuery还包含一个包装器和兼容性填充jQuery.proxy()

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

答案 1 :(得分: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:");