1

如何将函数的上下文应用于任何 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
4

1 回答 1

2

您可以将功能设置为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.aand定义中有一些问题foo.b,因为它们都是自引用this.b +=1,尤其会导致问题,因此您可能希望将函数更改为 and 之类的东西this._b +=alert(this._b)或者使用不同命名的函数。

于 2012-09-16T01:03:24.703 回答