Javascript 绑定对象文字方法不起作用
Javascript bind on object literal methods not working
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
returns 一个新函数,你必须把它分配给 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()
method 不会改变函数,而是 return 一个新函数。您没有对 return 值执行任何操作。以下将起作用:
ob.bind_part = ob.bind_part.bind(t);
.bind()
returns 您需要将其分配回调用对象的新函数。
ob.bind_part = ob.bind_part.bind(t);
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
returns 一个新函数,你必须把它分配给 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()
method 不会改变函数,而是 return 一个新函数。您没有对 return 值执行任何操作。以下将起作用:
ob.bind_part = ob.bind_part.bind(t);
.bind()
returns 您需要将其分配回调用对象的新函数。
ob.bind_part = ob.bind_part.bind(t);