大家好,欢迎来到IT知识分享网。
class类简介
JavaScript 语言中,生成实例对象的传统方法是通过构造函数。ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。
// Class类代替构造函数 class Point {
// Point 上 constructor(x, y) { this.x = x; this.y = y; } // Point.prototype 上 toString() { return '(' + this.x + ', ' + this.y + ')'; } } var per = new Point(1, 2); // 实例对象 console.log(per); // Point {x: 1, y: 2}
基本上,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。
上面代码定义了一个“类”,可以看到里面有一个constructor()方法,这就是构造方法,而this关键字则代表实例对象。这种新的 Class 写法,本质上与本章开头的 ES5 的构造函数Point是一致的。
Point类除了构造方法,还定义了一个toString()方法。注意,定义toString()方法的时候,前面不需要加上function这个关键字,直接把函数定义放进去了就可以了。另外,方法与方法之间不需要逗号分隔,加了会报错。
ES6 的类,完全可以看作构造函数的另一种写法。
class Point { // ... } console.log(typeof Point); // "function" console.log(Point === Point.prototype.constructor); // true
上面代码表明,类的数据类型就是函数,类本身就指向构造函数。
使用的时候,也是直接对类使用new命令,跟构造函数的用法完全一致。
class Person { doStuff() { console.log('stuff'); } } const per = new Person(); per.doStuff(); // "stuff"
构造函数的prototype属性,在 ES6 的“类”上面继续存在。事实上,类的所有方法都定义在类的prototype属性上面。
class Point { constructor() { // ... } toString() { // ... } toValue() { // ... } } // 等同于 Point.prototype = { constructor() {}, toString() {}, toValue() {}, };
因此,在类的实例上面调用方法,其实就是调用原型上的方法。
class B {} const b = new B(); b.__proto__.constructor === B.prototype.constructor // true
上面代码中,b是B类的实例,它的constructor()方法就是B类原型的constructor()方法。
由于类的方法都定义在prototype对象上面,所以类的新方法可以添加在prototype对象上面。Object.assign()方法可以很方便地一次向类添加多个方法。
class B {} const b = new B(); // 给类添加方法 Object.assign(B.prototype, { toString() {}, toValue() {} });
prototype对象的constructor()属性,直接指向“类”的本身,这与 ES5 的行为(指向构造函数本身)是一致的。
B.prototype.constructor === B)
constructor 方法
constructor()方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor()方法,如果没有显式定义,一个空的constructor()方法会被默认添加。
class B {} // 等同于 class B { constructor() {} }
上面代码中,定义了一个空的类Point,JavaScript 引擎会自动为它添加一个空的constructor()方法。
constructor()方法默认返回实例对象(即this)。
class Foo { constructor() { return this; // 默认隐式返回this } } var foo = new Foo(); console.log(foo instanceof Foo); // true
因此,完全可以指定返回另外一个对象。
class Foo { constructor() { return Object.create(null); // 将this指向一个空对象 } } var foo = new Foo(); // 方法1:验证 console.log(foo instanceof Foo); // false // 方法2:验证 console.log(Foo.prototype.isPrototypeOf(foo)); // false
上面代码中,constructor()函数返回一个全新的对象,结果导致实例对象不是Foo类的实例。
类必须使用new调用,否则会报错。这是它跟普通构造函数的一个主要区别,后者不用new也可以执行。
// 构造函数执行 function Person() { console.log("hello"); } Person(2, 5); // hello // 类执行 class Foo { constructor() { console.log("world"); } } new Foo(); // world
类的实例
生成类的实例的写法,与 ES5 完全一样,也是使用new命令。前面说过,如果忘记加上new,像函数那样调用Class,将会报错。
class Point { // ... } // 报错 var point = Point(2, 3); // 正确 var point = new Point(2, 3);
与 ES5 一样,实例的属性除非显式定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class上)。
//定义类 class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return '(' + this.x + ', ' + this.y + ')'; } } var point = new Point(2, 3); point.toString() // (2, 3) point.hasOwnProperty('x') // true point.hasOwnProperty('y') // true point.hasOwnProperty('toString') // false point.__proto__.hasOwnProperty('toString') // true
上面代码中,x和y都是实例对象point自身的属性(因为定义在this对象上),所以hasOwnProperty()方法返回true,而toString()是原型对象的属性(因为定义在Point类上),所以hasOwnProperty()方法返回false。这些都与 ES5 的行为保持一致。
与 ES5 一样,类的所有实例共享一个原型对象。
class B { constructor(x, y) { this.x = x; this.y = y } setName() { console.log('setName'); } } let b1 = new B(); let b2 = new B(); b1.setName(); // setName b2.setName(); // setName console.log(b1.prototype === b2.prototype); // true
上面代码中,p1和p2都是Point的实例,它们的原型都是Point.prototype,所以__proto__属性是相等的。
Class 表达式
与函数一样,类也可以使用表达式的形式定义。
const MyClass = class Me { getClassName() { return Me.name; } };
面代码使用表达式定义了一个类。需要注意的是,这个类的名字是Me,但是Me只在 Class 的内部可用,指代当前类。在 Class 外部,这个类只能用MyClass引用。
如果类的内部没用到的话,可以省略Me,也就是可以写成下面的形式。
let myClass = class {}
采用 Class 表达式,可以写出立即执行的 Class。
// 等同于创建myClass实例对象 let myClass = new class { constructor(name, age) { this.name = name; this.age = age; } sayName() { console.log(this.name + ":" + this.age); } }('james', 36); myClass.sayName(); // james:36
上面代码中,myClass是一个立即执行的类的实例。
注意点:
1、默认严格模式
2、不存在变量提升
// 类执行 new Foo(); // Cannot access 'Foo' before initialization 初始化前无法访问类 // 定义一个类 class Foo {}
3、name属性
class Point {} console.log(Point.name); // Point
4、Generator 方法
如果某个方法之前加上星号(*),就表示该方法是一个 Generator 函数。
class Foo { constructor(...args) { this.args = args; } *[Symbol.iterator]() { for (let arg of this.args) { yield arg; } } } let init = new Foo('hello', 'world'); for (let x of init) { console.log(x); } // hello // world
上面代码中,Foo类的Symbol.iterator方法前有一个星号,表示该方法是一个 Generator 函数。Symbol.iterator方法返回一个Foo类的默认遍历器,for...of循环会自动调用这个遍历器。
5、this 的指向
类的方法内部如果含有this,它默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。
class Logger { printName(name = 'there') { this.print(`Hello ${name}`); } print(text) { console.log(text); } } const logger = new Logger(); const { printName } = logger; printName(); // TypeError: Cannot read property 'print' of undefined
上面代码中,printName方法中的this,默认指向Logger类的实例。但是,如果将这个方法提取出来单独使用,this会指向该方法运行时所在的环境(由于 class 内部是严格模式,所以 this 实际指向的是undefined),从而导致找不到print方法而报错。
一个比较简单的解决方法是,在构造方法中绑定this,这样就不会找不到print方法了。
class Logger { constructor() { this.printName = this.printName.bind(this); } // ... }
另一种解决方法是使用箭头函数。
class Obj { constructor() { this.getThis = () => this; } } const myObj = new Obj(); myObj.getThis() === myObj // true
箭头函数内部的this总是指向定义时所在的对象。上面代码中,箭头函数位于构造函数内部,它的定义生效的时候,是在构造函数执行的时候。这时,箭头函数所在的运行环境,肯定是实例对象,所以this会总是指向实例对象。
静态方法
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
class Foo { static classMethod() { console.log('hello'); } } Foo.classMethod(); // 'hello' var foo = new Foo(); foo.classMethod() // TypeError: foo.classMethod is not a function
上面代码中,Foo类的classMethod方法前有static关键字,表明该方法是一个静态方法,可以直接在Foo类上调用(Foo.classMethod()),而不是在Foo类的实例上调用。如果在实例上调用静态方法,会抛出一个错误,表示不存在该方法。
注意,如果静态方法包含this关键字,这个this指的是类,而不是实例。
class Foo { static bar() { this.baz(); } static baz() { console.log('hello'); } baz() { console.log('world'); } } Foo.bar() // hello
上面代码中,静态方法bar调用了this.baz,这里的this指的是Foo类,而不是Foo的实例,等同于调用Foo.baz。另外,从这个例子还可以看出,静态方法可以与非静态方法重名。
父类的静态方法,可以被子类继承。
class Foo { static classMethod() { console.log('hello'); } } class Bar extends Foo {} // 声明一个子类继承父类 Bar.classMethod() // 'hello'
上面代码中,父类Foo有一个静态方法,子类Bar可以调用这个方法。
静态方法也是可以从super对象上调用的。
class Foo { static classMethod() { return 'hello'; } } class Bar extends Foo { static classMethod() { return super.classMethod() + ', too'; } } Bar.classMethod() // "hello, too"
实例属性的新写法
实例属性除了定义在constructor()方法里面的this上面,也可以定义在类的最顶层。
class IncreasingCounter { constructor() { this._count = 0; } get value() { console.log('Getting the current value!'); return this._count; } increment() { this._count++; } }
上面代码中,实例属性this._count定义在constructor()方法里面。另一种写法是,这个属性也可以定义在类的最顶层,其他都不变。
class IncreasingCounter { constructor() { this._count = 0; } get value() { console.log('Getting the current value!'); return this._count; } increment() { this._count++; } }
上面代码中,实例属性_count与取值函数value()和increment()方法,处于同一个层级。这时,不需要在实例属性前面加上this。
这种新写法的好处是,所有实例对象自身的属性都定义在类的头部,看上去比较整齐,一眼就能看出这个类有哪些实例属性。
class Foo { baz = 'hello'; bar = 'world'; constructor() { } } var f = new Foo(); console.log(f.baz + ' ' + f.bar); // hello world
上面的代码,一眼就能看出,foo类有两个实例属性,一目了然。另外,写起来也比较简洁。
静态属性
静态属性指的是 Class 本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性。
class Foo {} // 定义一个静态属性 Foo.prop = 1; console.log(Foo.prop); // 1 var p = new Foo(); console.log(p.prop); // undefined
上面的写法为Foo类定义了一个静态属性prop。
因为 ES6 明确规定,Class 内部只有静态方法,没有静态属性。现在有一个提案提供了类的静态属性,写法是在实例属性的前面,加上static关键字。
class Foo { // 定义一个静态属性 static prop = 1; } console.log(Foo.prop); // 1 var p = new Foo(); console.log(p.prop); // undefined
这个新写法大大方便了静态属性的表达。
// 老写法 class Foo { // ... } Foo.prop = 1; // 新写法 class Foo { static prop = 1; }
私有方法和私有属性
私有方法和私有属性,是只能在类的内部访问的方法和属性,外部不能访问。这是常见需求,有利于代码的封装,但 ES6 不提供,只能通过变通方法模拟实现。
一种做法是在命名上加以区别。
class Widget { // 公有方法 foo(baz) { this._bar(baz); } // 私有方法 _bar(baz) { return this.snaf = baz; } // ... }
上面代码中,_bar()方法前面的下划线,表示这是一个只限于内部使用的私有方法。但是,这种命名是不保险的,在类的外部,还是可以调用到这个方法。
class Widget { foo (baz) { bar.call(this, baz); } // ... } function bar(baz) { return this.snaf = baz; }
上面代码中,foo是公开方法,内部调用了bar.call(this, baz)。这使得bar()实际上成为了当前类的私有方法。
还有一种方法是利用Symbol值的唯一性,将私有方法的名字命名为一个Symbol值。
const bar = Symbol('bar');
const snaf = Symbol('snaf');
export default class myClass {
// 公有方法
foo(baz) {
this[bar](baz);
}
// 私有方法
[bar](baz) {
return this[snaf] = baz;
}
// ...
};
上面代码中,bar和snaf都是Symbol值,一般情况下无法获取到它们,因此达到了私有方法和私有属性的效果。但是也不是绝对不行,Reflect.ownKeys()依然可以拿到它们。
in运算符
try...catch结构可以用来判断是否存在某个私有属性。
class A { use(obj) { try { obj.#foo; } catch { // 私有属性 #foo 不存在 } } } const a = new A(); a.use(a); // 报错
这样的写法很麻烦,可读性很差,V8 引擎改进了in运算符,使它也可以用来判断私有属性。
class A { use(obj) { if (#foo in obj) { // 私有属性 #foo 存在 } else { // 私有属性 #foo 不存在 } } }
上面示例中,in运算符判断当前类A的实例,是否有私有属性#foo,如果有返回true,否则返回false。
in也可以跟this一起配合使用。
class A { #foo = 0; m() { console.log(#foo in this); // true console.log(#bar in this); // false } }
注意,判断私有属性时,in只能用在定义该私有属性的类的内部。
class A { #foo = 0; static test(obj) { console.log(#foo in obj); } } A.test(new A()) // true A.test({}) // false class B { #foo = 0; } A.test(new B()) // false
上面示例中,类A的私有属性#foo,只能在类A内部使用in运算符判断,而且只对A的实例返回true,对于其他对象都返回false。
子类从父类继承的私有属性,也可以使用in运算符来判断。
class A { #foo = 0; static test(obj) { console.log(#foo in obj); } } class SubA extends A {}; A.test(new SubA()) // true
上面示例中,SubA从父类继承了私有属性#foo,in运算符也有效。
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/31936.html
