Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!