开发者

How do I insert something into a prototype chain?

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) {
  va开发者_如何学Pythonr 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?


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());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜