基于另一个对象的属性定义对象的属性
我使用anotherFunction
函数基于来自对象someObject
的someFunction
定义了一个名为anotherObject
的对象。基于另一个对象的属性定义对象的属性
var someObject={
someFunction:function(){
return this;
}
};
console.log(someObject.someFunction()===someObject);//true
var someFunc=someObject.someFunction;
console.log(someFunc===someObject.someFunction);//true
//the function does not have the same context as that of the function called earlier...
console.log(someFunc()===someObject);//false
var anotherObject={
anotherFunction:someObject.someFunction
};
console.log(anotherObject.anotherFunction===someObject.someFunction);//true
console.log(anotherObject[anotherFunction]()===anotherObject);//true;
console.log(anotherObject.anotherFunction()===someObject);//false
Firefox Scratchpad报告未定义功能anotherFunction
。
就是这样的JavaScript函数实际工作中,someFunction
是一个函数,它的责任是在当前背景下返回this
,不管是这一个:
var someFunc=someObject.someFunction;
您可以使用叫它致电或与你喜欢的任何环境中应用:
var myobj = {};
console.log(someFunc.call(myobj)===myobj);//true
console.log(someFunc.apply(myobj)===myobj);//true
不管你通过什么作为第一个参数在call
和apply
,你的函数会返回一个非常对象。所以当你看到你的函数做它应该做的事情,但是如果你希望它总是返回你的第一个对象someObject
,你不需要使用this
关键字。
阅读my answer到How does JavaScript .prototype work?
,我试图在前两部分中深入探讨这个概念。
而且也这是你可以找到关于这个概念的最好的资源之一:
我想知道为什么函数'someObject.someFunction'没有被复制到'anotherObject.anotherFunction'.I确实了解了一点关于调用和应用 – vamsiampolu
@ user2309862:你是什么意思'未被复制?当你像'anotherFunction:someObject.someFunction'一样创建你的函数时,它只会创建对原始函数的引用。 –
你是说,将一个属性添加到已经传递给一个更高阶函数的函数将会修改原始函数 – vamsiampolu
(函数(){})==(函数(){}) – bjb568
'anotherObject [anotherFunction] ()'是垃圾 – Bergi
你的问题到底是什么? – Bergi