正如你自己所說:你有一個功能對象。函數是在JS對象,就像對象常量數組,或其他任何東西:一個功能可以分配的屬性和方法的意願:
var someAnonFunction = function(foo)
{
console.log(this);
console.log(this === someAnonFunction);//will be false most of the time
};
someAnonFunction.x = 123;//assign property
someAnonFunction.y = 312;
someAnonFunction.divide = function()
{
console.log(this === someAnonFunction);//will be true most of the time
return this.x/this.y;//divide properties x & y
};
someAnonFunction.divide();
在這種情況下,函數對象,通過引用已分配引用了名爲divide
的匿名函數(當然,對匿名函數的引用被稱爲「鴻溝」)。所以這裏根本沒有原型參與。你要知道,你這樣自己說:所有的對象都可以追溯到Object.prototype
,就試試這個:
console.log(someAnonFunction.toString === Function.prototype.toString);//functions are stringified differently than object literals
console.log(someAnonFunction.hasOwnProperty === Object.prototype.hasOwnProperty);//true
或者,也許這更是明確表示:方法/屬性調用是如何解析爲一個簡單的方案
[ F.divide ]<=========================================================\ \
F[divide] ===> JS checks instance for property divide | |
/\ || | |
|| || --> property found @instance, return value-------------------------------| |
|| || | |
|| ===========> Function.prototype.divide could not be found, check prototype | |
|| || | |
|| ||--> property found @Function.prototype, return-----------------------| |
|| || | |
|| ==========> Object.prototype.divide: not found check prototype? | |
|| || | |
|| ||--> property found @Object.prototype, return---------------------|_|
|| || |=|
|| =======>prototype is null, return "undefined.divide"~~~~~~~~~~~~~~~|X|
|| \/
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~< TypeError can't read property 'x' of undefined
由此得出,如果你想上面的代碼中使用原型的工作,你必須增加一個原型各種各樣的(在這種情況下,Function.prototype
):在JS的值。要知道這不是被推薦的,實際上改變「原生」的原型往往是不被接受的。仍然:
Function.prototype.divide = function (a, b)
{
a = +(a || 0);//coerce to number, use default value
b = +(b || 1) || 1;//division by zeroe is not allowed, default to 1
return a/b;
};
function someFunction()
{
return 'someString';
};
var another = function(a, b)
{
return a + b;
};
someFunction.divide(12, 6);//will return 2
another.divide(12, 4);//3
在這兩種情況下,所述功能對象,由名稱(someFunction
或another
)引用將掃描名爲divide
屬性,該屬性是找不到的。然後,它會掃描Function.prototype
,發現這樣的屬性。
如果不是這樣,JS還會檢查Object.prototype
,如果失敗了,它最終會拋出一個錯誤。
我已經發布了相當長的答案在等這個問題而回:
What makes my.class.js so fast?(與原型鏈交易)
Objects and functions in javascript(功能概括< =>對象< =>構造函數)
What are the differences between these three patterns of "class" definitions in JavaScript? (一些更多的信息,仍然)
Javascript - Dynamically change the contents of a function(隱約觸及匿名函數,分配給變量和屬性,並改變其上下文)
我在Chrome中運行代碼,它說:Uncaught TypeError:Object function(num1,num2){ return num1 + num2; }沒有方法'divide' – andri 2013-03-02 12:04:34
您確定這不是一個架構問題嗎?實際上,分隔不會是addNum的子功能。相反,他們會有一個父類/對象,他們可以共享變量和屬性並對它們進行數學運算? – 2013-03-02 12:16:31
我在http://doctrina.org/Javascript-Objects-Prototypes.html上讀到這一行 – testndtv 2013-03-02 12:40:33