javascriptprototypedefineproperty

JavaScript: How to add a not enumerable method (not a property) in Object.defineProperty


I want to add a method (not a property) to Array.prototype, but I dont want it to be enumerable and mess all for(...in...) in third party libraries.

//... Example:
//... Only push the value if it is not false
Array.prototype.pushValue = function(value){
    if(value){ this.push(value); }
}

var pieces = [];
pieces.pushValue(0);
pieces.pushValue(1);
pieces.pushValue(2);
pieces.pushValue(null);
console.log(pieces.join(",")); //outputs 1,2

for(var k in pieces){
    console.log(k); //outputs 0,1 and pushValue
}

I know I can use "hasOwnProperty" on my code to detect my custom methods, but I cannot change all code from third party libraries to add this verification.

Regardless if it's a good practice or not to add a method to Array.prototype, is it possible to add it as non enumerable?


Solution

  • You can use Object.defineProperty() like this:

    Object.defineProperty(Array.prototype, 'test', {
      value: () => console.log(1),
      enumerable: false,
    });

    This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (for...in loop or Object.keys method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, values added using Object.defineProperty() are immutable and not enumerable.