这很简单:
function Ninja(name)
{//this points to Ninja object inside constructor scope
this.name = name;
this.changeName = function(newname)
{//method of Ninja, this points to context object, ie Ninja
this.name = newname;//accesses the name property of Ninja
this.anotherFunction = function(newname2)
{//defines new method for this ==> Ninja object
this.name2 = newname2;//context object is Ninja
};
};
}
var foo = new Ninja('foobar');
foo.name;//foobar
foo.changeName;//function, is defined in constructor
typeof foo.anotherFunction//undefined because it's assigned when the changeName method is called!
foo.changeName('Me');
foo.name;//Me
foo.anotherFunction('You');//works: changeName was called, and assigned anotherFunction to foo (instance of Ninja)
foo.name2;//You
发生了什么:简单,通过调用 changeName 方法,anotherFunction
定义并分配给this
. 当时this
引用了该对象,因此该方法被分配给调用该方法Ninja
的实例。在调用该方法之前,该方法根本不存在。Ninja
changeName
changeName
anotherFunction
虽然这可能看起来无用或愚蠢,但它确实是有道理的。您需要记住的是,函数/方法本质上是独立的对象。在这段代码中,它们恰好被定义为属性/方法,但它们不需要这样使用。回到上面的代码:
foo.name;//Me
bar = {};//some object
foo.changeName.apply(bar,['You']);
foo.name;//Me, nothing has changed, the changeName method was applied to the bar object
bar.name;//You, in the apply call, this pointed to bar, not foo
typeof bar.anotherFunction;//function
//You could even create the anotherFunction globally:
// JUST TO SHOW YOU CAN, THIS IS DANGEROUS
// ONLY USE THIS IF YOU KNOW WHAT THE POSSIBLE CONSEQUESES ARE!
foo.changeName.call();//in global scope
typeof antoherFunction;//function ==> this function is now globally available
该changeName
方法可以应用于任何对象,添加新方法,更改/添加某些属性到该特定实例。