开发者

Add a method to Object primative, but not have it come up as a property

开发者 https://www.devze.com 2023-03-19 17:55 出处:网络
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 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 开发者_如何学Cobject. 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?


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).

0

精彩评论

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