将函数的上下文应用于javascript变量

Applying context of functions to javascript variable?

本文关键字:javascript 变量 应用于 上下文 函数      更新时间:2023-09-26

如何将函数的上下文应用于任何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.afoo.b的定义中存在一些问题,因为它们都是自引用。this.b +=1尤其会引起问题,因此您可能希望将函数更改为类似this._b +=alert(this._b)的函数,或者使用不同名称的函数。