bind方法不会将't'变量作为新的'this'关键字转移到"ob.bind_part()"对象文字函数?
var ob = {
"first": function() {
console.log("first function");
var t = "new bind";
ob.bind_part.bind(t);
},
"bind_part": function() {
console.log(this.toString());
}
};
(function() {
ob.first();
ob.bind_part(); // returns the 'ob' object instead of the bind
})();
但是,如果使用了"call",则不是绑定
ob.bind_part.call(t); //THIS WORKS
它有效吗?
知道为什么绑定不起作用吗?
感谢
Function.bind
返回一个新函数,您必须将其分配给obj.bind_part
var ob = {
"first": function() {
console.log("first function");
var t = "new bind";
ob.bind_part = ob.bind_part.bind(t);
},
"bind_part": function() {
console.log(this.toString());
}
};
(function() {
ob.first();
ob.bind_part(); // returns "new bind"
})();
.bind()
方法不会对函数进行变异,而是返回一个新函数。您没有对返回值执行任何操作。以下方法可行:
ob.bind_part = ob.bind_part.bind(t);
.bind()
返回一个新函数,您需要将其分配回调用对象。
ob.bind_part = ob.bind_part.bind(t);