Extending native JavaScript objects with Object.create

I've been reading Inheritance and the prototype chain on the Mozilla Developer Network and have been wondering about something it said.

One mis-feature that is often used is to extend Object.prototype or one of the other built-in prototypes.

I understand why adding a new function onto a native object's prototype would cause issues.

Array.prototype.first = function() { return this[0]; };

But suppose someone created a new array and wanted it to have all the functionality of Array via its prototype chain, and they did something like this:

function MyArray() { Array.apply(this, arguments); }
MyArray.prototype = Object.create(Array.prototype);
MyArray.prototype.first = function() { return this[0]; };

Is this method of extending (inheriting from) a native object also considered bad practice? If so, what problems would it cause?


This is a general software architecture question, so there can be a lot of different perspectives on what is right or wrong.

My opinion is that native objects should stay native objects. If I were an outsider looking at a code base with a native object being modified, I would be very confused. I could be a javascript guru, but I would be lost and confused at first.

A better way of doing the exact same thing, is instead of extending through inheritance, to extend through composition.

function ListClass() {
  var arr = [];
  return {
     first: function() { return arr[0]; },
     get: function(i) { return arr[i]; },
     push: arr.push 
  };
}

Your idea is completely valid javascript. The only objection would be code clarity.

链接地址: http://www.djcxy.com/p/27242.html

上一篇: 有没有办法给所有的对象一个方法而不修改Object.prototype?

下一篇: 用Object.create扩展本地JavaScript对象