Add a method to Object primative, but not have it

2020-08-01 01:47发布

Object has Object.toString, a method that you can call on any object. When iterating through the property list, or, just doing a console.log(obj), you will not see toString come up as a property of an object. It is hidden.

I want to add a new method on to the Object primitive, using Object.prototype.myMethod. I do not however want it to come up every time I iterate through an object. I would like it hidden.

How can I do that?

1条回答
兄弟一词,经得起流年.
2楼-- · 2020-08-01 02:19

You can do that with ECMAScript 5's defineProperty [docs]:

Object.defineProperty(Object.prototype, 'myMethod', {
    value: function() {
        // your function
    },
    enumerable: false // default is already `false`
});

Obviously this does not work in browsers that don't support ES5 (especially IE8 and earlier).

查看更多
登录 后发表回答