Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda