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

将函数上下文应用于javascript变量?,javascript,Javascript,如何将函数的上下文应用于任何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.fu

如何将函数的上下文应用于任何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();
…但如果您希望它被
某物的所有实例继承,则需要将其设置为
某物。prototype

var moo;
Something.prototype = foo;
moo = new Something();
moo.a();

您对
foo.a
foo.b
的定义中存在一些问题,因为它们都是自引用
this.b+=1
会特别引起问题,因此您可能希望将函数更改为类似
this.\u b+=
警报(this.\u b)
,或者使用不同名称的函数。

+1我认为[需要[prototype]]路由;它看起来像jQuery仿真方法。