【发布时间】:2013-01-05 06:42:47
【问题描述】:
鉴于 ES 5.1 标准规定...
1)http://es5.github.com/#x13.2脚下的注释
NOTE A prototype property is automatically created for every function,
to allow for the possibility that the function will be used as a constructor.
2)http://es5.github.com/#x15.3.5.2
NOTE Function objects created using Function.prototype.bind do not have
a prototype property.
(这意味着所有其他功能都可以)
...为什么内置函数不再有原型属性?:
[].push.prototype; //undefined
Math.max.prototype; //undefined
此外,即使为它们分配了原型属性,这些内置函数也不能用作构造函数:
[].push.prototype = {};
[].push.prototype; //[object Object]
new [].push(); //TypeError: function push() { [native code] } is not a constructor
相反,从用户定义的对象中删除原型属性仍然允许它用作构造函数,并且实际上将通用对象分配给生成的实例的 [[prototype]]:
var A = function() {};
A.prototype = undefined;
A.prototype; //undefined
(new A()).__proto__; //[object Object]
现在内置函数的子类型是构造函数还是函数?
[在大多数现代浏览器中测试]
【问题讨论】:
-
这可能是因为它们是用非javascript代码实现的,因此可能没有
prototype。这纯属猜测。 -
"此外,即使为它们分配了原型属性,这些内置函数也不能用作构造函数:" -- 现在这行让我感兴趣了
-
@SnakesandCoffee 好主意;但是,我看不出本机函数不能成为构造函数的原因。毕竟,
new console.log(Chrome 原生)会抛出illegal invocation,而不是not a constructor。此外,Array是原生的(在 chrome 中),但它可以作为构造函数调用(很容易)。 -
这可能是因为他们不希望内置函数被篡改。存在更多可能的安全风险。
-
"not a constructor" 通常在尝试的构造函数不是函数(但
[].push是)时抛出。