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

9.8.5 Subclasses and ECMAScript 5

9.8.5 Subclasses and ECMAScript 5


Example 9-22 demonstrates subclassing using ECMAScript 5 features. It defines a StringSet class as a subclass of the AbstractWritableSet class from Example 9-16 . The main feature of this example is the use of Object.create() to create a prototype object that inherits from the superclass prototype and also define the properties of the newly created object. The difficulty with this approach, as mentioned earlier, is that it requires the use of awkward property descriptors.

Another interesting point about this example is that it passes null to Object.create() to create an object that inherits nothing. This object is used to store the members of the set, and the fact that it has no prototype allows us to use the in operator with it instead of the hasOwnProperty() method.

Example 9-22. StringSet: a set subclass using ECMAScript 5

function StringSet() { this.set = Object.create(null); // Create object with no proto this.n = 0; this.add.apply(this, arguments);

}

// Note that with Object.create we can inherit from the superclass prototype // and define methods in a single call. Since we don't specify any of the // writable, enumerable, and configurable properties, they all default to false. // Readonly methods makes this class trickier to subclass. StringSet.prototype = Object.create(AbstractWritableSet.prototype, {

constructor: { value: StringSet }, contains: { value: function(x) { return x in this.set; } }, size: { value: function(x) { return this.n; } }, foreach: { value: function(f,c) { Object.keys(this.set).forEach(f,c); } }, add: {

value: function() { for(var i = 0; i < arguments.length; i++) {

if (!(arguments[i] in this.set)) { this.set[arguments[i]] = true; this.n++;

} } return this;

} }, remove: {

value: function() { for(var i = 0; i < arguments.length; i++) {

if (arguments[i] in this.set) { delete this.set[arguments[i]]; this.n--;

} } return this;

} } });

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