它在我写的时候起作用(http://jsfiddle.net/XJwvP/):
var Person = function(name) { this.name = name; }
Person.prototype = function () {
var sayHello = function (name) {
alert("Hello, " + name);
};
return {
sayHello: sayHello
};
}();
var person = new Person("Max");
person.sayHello("James");
当我写的时候它不起作用( http://jsfiddle.net/ZKd4R/ ):
Array.prototype = function () {
var sayHello = function (name) {
alert("Hello, " + name);
};
return {
sayHello: sayHello
};
}();
var array = new Array();
array.sayHello("James");
错误:
Uncaught TypeError: Object [object Array] has no method 'sayHello'
为什么我不能对 Array 对象使用相同的方法?
最佳答案
像你一样替换 Array.prototype
不会影响新的 Array
实例,因为 Array
构造函数在语言中是特殊的(它是内置构造函数)。规范说明在 15.4.2.1 :
The [[Prototype]] internal property of the newly constructed object is set to the original Array prototype object, the one that is the initial value of Array.prototype (15.4.3.1).
如果你勾选15.4.3.1 ,你会注意到 Array.prototype
也不是 [[Writable]]。我刚刚在 Chrome 控制台中测试了它:
var ap = Array.prototype;
Array.prototype = {};
ap == Array.prototype; // true
关于javascript - 揭示原型(prototype)模式不适用于 Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18905438/