如何将函数的上下文应用于任何 javascript 对象?所以我可以更改“this”在函数中的含义。
例如:
var foo = {
a: function() {
alert(this.a);
},
b: function() {
this.b +=1;
alert (this.b);
}
var moo = new Something(); // some object
var moo.func.foo = foo; // right now this is moo.func
// how do I apply/change the context of the foo functions to moo?
// so this should equal moo
moo.a(); // this should work
最佳答案
你可以在 moo
上设置函数:
var moo = new Something();
moo.a = foo.a;
moo.a();
...但是如果你想让它被 Something
的所有实例继承,你需要在 Something.prototype
上设置它:
var moo;
Something.prototype = foo;
moo = new Something();
moo.a();
foo.a
和 foo.b
的定义有一些问题,因为它们都是自引用 this.b +=1
尤其会引起问题,因此您可能希望将函数更改为 this._b +=
和 alert(this._b)
之类的函数,或使用不同的名称功能。
关于javascript - 将函数上下文应用于javascript变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12443601/