如何将某些内容插入原型链?
我有一个“类”,它本质上是一个增强的数组:
function NamedArray(name) {
var result = [];
result.name = name;
return result;
};
var cheeses = new NamedArray('Cheeses');
这非常有效。不起作用的是为这个“类”添加原型:
NamedArray.prototype = {
nameInAllCaps: function() {
return this.name.toUpperCase();
}
};
cheeses.nameInAllCaps();
=> TypeError: Object #<Object> has no method 'nameInAllCaps'
我的第一个想法是将“原型”混合到结果
Array
中:
function NamedArray(name) {
var result = [];
result.name = name;
for (var prop in NamedArray.prototype) {
if (NamedArray.prototype.hasOwnProperty(prop) {
result[prop] = NamedArray.prototype[prop];
}
}
return result;
};
这可行,但它使每个实例都有自己的原型属性副本。有没有办法将NamedArray.prototype插入到结果
Array
的原型链中?
I have a "class" that is essentially a beefed-up Array
:
function NamedArray(name) {
var result = [];
result.name = name;
return result;
};
var cheeses = new NamedArray('Cheeses');
This works great. What doesn't work is adding a prototype for this "class":
NamedArray.prototype = {
nameInAllCaps: function() {
return this.name.toUpperCase();
}
};
cheeses.nameInAllCaps();
=> TypeError: Object #<Object> has no method 'nameInAllCaps'
My first thought was just to mix the "prototype" into the result
Array
:
function NamedArray(name) {
var result = [];
result.name = name;
for (var prop in NamedArray.prototype) {
if (NamedArray.prototype.hasOwnProperty(prop) {
result[prop] = NamedArray.prototype[prop];
}
}
return result;
};
This works, but it causes each instance to have its own copy of the prototype properties. Is there a way to insert NamedArray.prototype into the prototype chain of the result
Array
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
James,
问题是你的“构造函数”返回的东西不是由
new
创建的新分配的对象。 (相反,您从构造函数内部创建一个数组,然后返回该数组。)要纠正构造函数代码中这个令人困惑的方面,请考虑以下内容:
James,
The problem is that your "constructor" is returning something other than the newly-allocated object created by
new
. (Instead, you're creating an array from inside your constructor, and returning that.)To correct this confusing aspect of your constructor code, consider something like: