Search code examples
javascriptprototype-programming

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


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?


Solution

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