Home  >  Article  >  Web Front-end  >  Under what circumstances should javascript not add enumerable properties to Object.prototype?

Under what circumstances should javascript not add enumerable properties to Object.prototype?

伊谢尔伦
伊谢尔伦Original
2017-07-26 17:03:171438browse

Never add enumerable (Enumerable) properties to Object.prototype

If your code relies on a for..in loop to traverse the Object type properties, do not add any enumerable properties to Object.prototype.

But when enhancing the JavaScript execution environment, it is often necessary to add new properties or methods to the Object.prototype object. For example, you can add a method to get all the attribute names in an object:


Object.prototype.allKeys = function() { 
  var result = []; 
  for (var key in this) { 
    result.push(key); 
  } 
  return result; 
};

But the result is as follows:


({ a: 1, b: 2, c: 3}).allKeys(); // ["allKeys", "a", "b","c"]

A possible solution is to use functions instead of defining new methods on Object.prototype:


function allKeys(obj) { 
  var result = []; 
  for (var key in obj) { 
    result.push(key); 
  } 
  return result; 
}

But if you really need to If you add a new attribute to Object.prototype and do not want the attribute to be traversed in the for..in loop, you can use the Object.defineProject method provided by the ES5 environment:


Object.defineProperty(Object.prototype, "allKeys", { 
  value: function() { 
    var result = []; 
    for (var key in this) { 
      result.push(key); 
    } 
    return result; 
  }, 
  writable: true, 
  enumerable: false, 
  configurable: true 
});

The key part of the above code is to set the enumerable attribute to false. In this case, the property cannot be traversed in the for..in loop.

The above is the detailed content of Under what circumstances should javascript not add enumerable properties to Object.prototype?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn