Add methods to Array.prototype, without the side effects

好久不见. 提交于 2019-12-24 01:54:57

问题


I'd like to add an "insert" method on Arrays. So I'm doing it like this:

> Array.prototype.insert = function(index, element){
    this.splice(index, 0, element);
};

And it works:

> a = [1,2,3]
[1, 2, 3]
> a.insert(0, 4)
undefined
> a
[4, 1, 2, 3]

But there's an undesired side effect:

> for (i in a){console.log(i)}
0
1
2
3
insert

> for (i in a){console.log(a[i])}
4
1
2
3
function (index, element){
    this.splice(index, 0, element);
}

This behavior is not intended and breaks other libraries that I use. Is there any elegant solution for this?


回答1:


Object.defineProperty works, but it won't be supported in older browsers. (compatibility table)

Object.defineProperty(Array.prototype, 'insert', {
  enumerable: false,
  value: function(index, element){
    this.splice(index, 0, element);
  }
});

Demonstration




回答2:


In this loop inherited properties (insert method) are not displayed.

  for (i in a){if (a.hasOwnProperty(i)) {console.log(i)}}

So, every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

This method compatible with all browsers



来源:https://stackoverflow.com/questions/22387766/add-methods-to-array-prototype-without-the-side-effects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!