javascript - js 日志绑定对象
问题描述
我有一个绑定到对象的函数,如何访问与该函数在同一范围内的对象?
let f = function(){};
class A{}
f = f.bind(new A());
// console.log(f.bindedObject)
在方法中呢?
class B{
constructor(func){
this.func = func;
}
log(){
// console.log(this.func.bindedObject)
}
}
class A{}
let b = new B(function(){}.bind(new A()));
b.log()
解决方案
您可以覆盖该bind
方法
(function() {
let bind = Function.prototype.bind;
Function.prototype.bind = function(newThis) {
let bf = bind.apply(this, arguments);
bf.newThis = newThis;
return bf;
};
})();
var f = function() {};
var nf = f.bind({'hello':1});
console.log('newThis', nf.newThis);