JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

9.8.1 Making Properties Nonenumerable

9.8.1 Making Properties Nonenumerable


The Set class of Example 9-6 used a trick to store objects as set members: it defined an “object id” property on any object added to the set. Later, if other code uses that object in a for/inloop, this added property will be returned. ECMAScript 5 allows us to avoid this by making properties nonenumerable. Example 9-17 demonstrates how to do this with Object.defineProperty()and also shows how to define a getter function and how to test whether an object is extensible.

Example 9-17. Defining nonenumerable properties

// Wrap our code in a function so we can define variables in the function scope

(function() { // Define objectId as a nonenumerable property inherited by all objects. // When this property is read, the getter function is invoked. // It has no setter, so it is read-only. // It is nonconfigurable, so it can't be deleted. Object.defineProperty(Object.prototype, "objectId", {

get: idGetter, // Method to get value enumerable: false, // Nonenumerable configurable: false // Can't delete it

});

// This is the getter function called when objectId is read function idGetter() { // A getter function to return the id if (!(idprop in this)) { // If object doesn't already have an id if (!Object.isExtensible(this)) // And if we can add a property throw Error("Can't define id for nonextensible objects");

Object.defineProperty(this, idprop, { // Give it one now. value: nextid++, // This is the value writable: false, // Read-only enumerable: false, // Nonenumerable configurable: false // Nondeletable

}); } return this[idprop]; // Now return the existing or new value

};

// These variables are used by idGetter() and are private to this function var idprop = "|**objectId**|"; // Assume this property isn't in use var nextid = 1; // Start assigning ids at this #

}()); // Invoke the wrapper function to run the code right away

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/27854.html
友情链接It题库(ittiku.com)| 版权归yishouce.com所有| 友链等可联系 admin#yishouce.com|粤ICP备16001685号-1