老生常谈ES6中的类(3)

这里先创建一个匿名类表达式,然后立即执行。依照这种模式可以使用类语法创建单例,并且不会在作用域中暴露类的引用,其后的小括号表明正在调用一个函数,而且可以传参数给这个函数


我们可以通过类似对象字面量的语法在类中创建访问器属性

访问器属性

尽管应该在类构造函数中创建自己的属性,但是类也支持访问器属性。创建getter时,需要在关键字get后紧跟一个空格和相应的标识符;创建setter时,只需把关键字get替换为set即可

class CustomHTMLElement { constructor(element) { this.element = element; } get html() { return this.element.innerHTML; } set html(value) { this.element.innerHTML = value; } } var descriptor = Object.getOwnPropertyDescriptor(CustomHTMLElement.prototype, "html"); console.log("get" in descriptor); // true console.log("set" in descriptor); // true console.log(descriptor.enumerable); // false

这段代码中的CustomHTMLElement类是一个针对现有DOM元素的包装器,并通过getter和setter方法将这个元素的innerHTML方法委托给html属性,这个访问器属性是在CustomHTMLElement.prototype上创建的。与其他方法一样,创建时声明该属性不可枚举。下面这段代码是非类形式的等价实现

// 直接等价于上个范例 let CustomHTMLElement = (function() { "use strict"; const CustomHTMLElement = function(element) { // 确认函数被调用时使用了 new if (typeof new.target === "undefined") { throw new Error("Constructor must be called with new."); } this.element = element; } Object.defineProperty(CustomHTMLElement.prototype, "html", { enumerable: false, configurable: true, get: function() { return this.element.innerHTML; }, set: function(value) { this.element.innerHTML = value; } }); return CustomHTMLElement; }());

由上可见,比起非类等效实现,类语法可以节省很多代码。在非类等效实现中,仅html访问器属性定义的代码量就与类声明一样多

可计算成员名称

类和对象字面量还有更多相似之处,类方法和访问器属性也支持使用可计算名称。就像在对象字面量中一样,用方括号包裹一个表达式即可使用可计算名称

let methodName = "sayName"; class PersonClass { constructor(name) { this.name = name; } [methodName]() { console.log(this.name); } } let me = new PersonClass("huochai"); me.sayName(); // "huochai"

这个版本的PersonClass通过变量来给类定义中的方法命名,字符串"sayName"被赋值给methodName变量,然后methodName又被用于声明随后可直接访问的sayName()方法

通过相同的方式可以在访问器属性中应用可计算名称

let propertyName = "html"; class CustomHTMLElement { constructor(element) { this.element = element; } get [propertyName]() { return this.element.innerHTML; } set [propertyName](value) { this.element.innerHTML = value; } }

在这里通过propertyName变量并使用getter和setter方法为类添加html属性,并且可以像往常一样通过.html访问该属性

在类和对象字面量诸多的共同点中,除了方法、访问器属性及可计算名称上的共同点外,还需要了解另一个相似之处,也就是生成器方法

生成器方法

在对象字面量中,可以通过在方法名前附加一个星号(*)的方式来定义生成器,在类中亦是如此,可以将任何方法定义成生成器

class MyClass { *createIterator() { yield 1; yield 2; yield 3; } } let instance = new MyClass(); let iterator = instance.createIterator();


这段代码创建了一个名为MyClass的类,它有一个生成器方法createIterator(),其返回值为一个硬编码在生成器中的迭代器。如果用对象来表示集合,又希望通过简单的方法迭代集合中的值,那么生成器方法就派上用场了。数组、Set集合及Map集合为开发者们提供了多个生成器方法来与集合中的元素交互

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyjypx.html