Home > Web Front-end > JS Tutorial > body text

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

伊谢尔伦
Release: 2017-07-26 17:03:17
Original
1430 people have browsed it

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; 
};
Copy after login

But the result is as follows:


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

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; 
}
Copy after login

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 
});
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template