javascript函数指针和“;这个“;

javascript function pointer and "this"

本文关键字:这个 函数 指针 javascript      更新时间:2023-09-26

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

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

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

任何functionthis值都是在调用时确定的。function实际上与"对象"没有其他联系,只是它是否被称为object.method()method.call(object)

因此,要传递具有固定this值的function,需要绑定:

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:");