正如你自己所说:你有一个功能对象。函数是在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