如何将某些内容插入原型链?

发布于 2024-10-31 03:16:48 字数 876 浏览 3 评论 0原文

我有一个“类”,它本质上是一个增强的数组:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

高冷爸爸 2024-11-07 03:16:48

James,

问题是你的“构造函数”返回的东西不是由 new 创建的新分配的对象。 (相反,您从构造函数内部创建一个数组,然后返回该数组。)

要纠正构造函数代码中这个令人困惑的方面,请考虑以下内容:

function NamedArray(name) {
  this.name = name;
};

NamedArray.prototype = new Array();
NamedArray.prototype.nameInAllCaps =  function() {
  return this.name.toUpperCase();
}

c = new NamedArray("cheeses");
console.log(c.name);
console.log(c.nameInAllCaps());

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:

function NamedArray(name) {
  this.name = name;
};

NamedArray.prototype = new Array();
NamedArray.prototype.nameInAllCaps =  function() {
  return this.name.toUpperCase();
}

c = new NamedArray("cheeses");
console.log(c.name);
console.log(c.nameInAllCaps());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文