文章目录
class基本语法
ES6提供了更接近传统语言的写法,引入Class(类)的概念,作为对象的模板。通过class关键字,可以定义类。
ES6的class可以看作是一个语法糖,新的写法只是让对象的写法更加清晰、更像面向对象编程的语法。
// 普通构造函数
function Point(x, y){
this.x = x;
this.y = y;
}
Point.prototype.toString = function(){
return '(' + this.x + ',' + this.y + ')';
}
var p = new Point(1, 2);
// class改写
class Point {
constructor(x, y){ // 实例属性和方法
this.x = x;
this.y = y;
}
toString(){
return '(' + this.x + ',' + this.y + ')';
}
}
注意
- 定义’类’的方法的时候,前面不需要加function关键字,直接把函数定义放进去就可以了;
- 方法之间不需要逗号分隔,加了会报错。
ES6的类,完全可以看作构造函数的另一种写法
class Ponit{}
typeof Point // 'function'
Point === Point.prototype.constructor // true
类的数据类型是函数,类本身指向构造函数
使用的时候,也可以直接对类使用new命令
class Bar{
doStuff(){
console.log('stuff');
}
}
var b = new Bar();
b.doStuff() // 'stuff'
构造函数的prototype属性,在Es6的’类’上面继续存在。实际上,类的所有方法都定义在类的prototype属性上面。
class Point{
constructor(){}
toString(){}
toValue(){}
}
// 等同于
Point.prototype = {
constructor(){},
toString(){},
toValue(){}
}
在类的实例上面调用方法,其实是调用原型上的方法。
class B{}
let b = new B();
b.constructor === B.prototype.constructor // true
b是B的实例,它的constructor方法就是B类原型的constructor方法。
由于类的方法都定义在prototype对象上面,所以类的新方法可以添加在prototype对象上面。Object.assign方法可以一次向类添加多个方法。
class Point{
constructor(){}
}
Object.assign(Point.prototype, {
toString(){},
toValue(){}
})
prototype对象的constructor属性,直接指向’类’本身。
Point.prototype.constructor === Point // true
类的内部定义的所有方法,都是不可枚举的。
class Point{
constructor(){}
toString(){}
}
Object.keys(Point.prototype); // []
Object.getOwnPropertyNames(Point.prototype); // ['constructor', 'toString']
ES6,toString方法是Point类内部定义的方法,是不可枚举的。
var Point = function(x, y){
//....
}
Point.prototype.toString = function(){
//...
}
Object.keys(Point.prototype); // ['toString']
Object.getOwnPropertyNames(Point.prototype); // ['constructor', 'toString']
ES5,toString方法是可枚举的。
constructor方法
constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。
一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。
class Point{}
// 等同于
class Point{
constructor(){}
}
定义一个空的类Point,js会自动为它添加一个空的constructor方法。
constructor方法默认返回实例对象(this),完全可以指定返回另一个对象。
class Foo{
constructor(){
return Object.creat(null);
}
}
new Foo() instanceof Foo // false
constructor函数返回一个全新的对象,结果导致实例对象不是Foo类的实例。
类必须使用new调用,否则就会报错,而普通构造函数不用new也可以执行。
class Foo{
constructor(){
return Object.creat(null);
}
}
Foo()
// TypeError: Class constructor Foo cannot be invoked without 'new'
类的实例
生成类的实例也是使用new命令。实例的属性除非显式定义在其本身(定义在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的行为一致。
类的所有实例共享一个原型对象。
var p1 = new Point(1, 2);
var p2 = new Point(2, 3);
p1.__proto__ === p2.__proto__ // true
p1和p2都是Point的实例,他们原型都是Point.prototype,所以__proto__属性是相等的。
所以,可以通过实例的__proto__属性为’类’添加方法。
__proto__并不是语言本身的特性,是具体实现时添加的私有属性,虽然目前很多现在浏览器提供了这个私有属性,但不建议使用该属性,避免对环境产生依赖,生产环境中,我们可以使用Object.getPrototypeOf方法来获取实例对象的原型,然后再为原型添加方法或属性。
var p1 = new Point(2, 3);
var p2 = new Point(3, 2);
p1.__proto__.printName = function(){ return 'Oops' };
p1.printName(); // Oops
p2.printName(); // Oops
var p3 = new Point(4, 3);
p3.printName(); // Oops
代码在p1的原型上添加了printName方法,由于p1的原型就是p2的原型,所以p2也可以调用该方法,在后新建实例p3也可以调用该方法,这就意味着,使用实例的__proto__属性改写原型,必须谨慎,不推荐使用,因为这会改变“类”的原始定义,影响所有实例。
取值函数和存值函数
在“类”的内部使用get和set关键字,对某个属性设置存值函数和取值函数,拦截改属性的存取行为。
class MyClass {
constructor(){
// ...
}
get prop(){
return 'getter'
}
set prop(value){
console.log('setter: ' + value);
}
}
let inst = new MyClass();
inst.prop = 123;
// 'setter: 123'
inst.prop // 'getter'
代码中,prop属性有对应的存值函数和取值函数,因此赋值和读取行为都被自定义了。
存值函数和取值函数是这是在属性的Descriptor对象上的。
class CustomHTMLElement {
constructor(element){
this.element = element;
}
get html() {
return this.element.innerHTML;
}
set html(){
this.element.innerHTML = value;
}
}
var descriptor = Object.getOwnPropertyDescriptor(
CustomHTMLElement.prototype, 'html'
)
'get' in descriptor // true
'set' in descriptor // true
代码中,存值函数和取值函数是定义在html属性的描述对象上,与ES5完全一致。
属性表达式
类的属性名,可以采用表达式。
let methodName = 'getArea';
class Square{
constructor(length){
// ...
}
[methodName]() {
// ...
}
}
Square类的方法名getArea,是从表达式得到的。
实例属性的新写法
实例属性除了定义在constructor()方法里面的this上面,也可以定义在类的最顶层。
class IncreasingCounter{
constructor(){
this._count = 0;
}
get value(){
console.log('get value!');
return this._count;
}
increment(){
this._count++;
}
}
代码中,实例属性this._count定义在constructor()方法里面。另外一种写法是,这个属性定义在类的最顶层,其他都不变。
class IncreasingCounter{
_count = 0;
get value(){
console.log('get value!');
return this._count;
}
increment(){
this._count++;
}
}
代码中,实例属性_count与取值函数value()和increment()方法,处于同一个层级。这是,不需要在实例属性前面加上this。
这种写法的好处是,所有实例对象自身的属性都定义在类的头部,看上去比较整齐,一眼就能看出这个类有哪些实例属性。
class Foo{
bar = 'hello';
baz = 'world';
constructor(){
// ...
}
}
代码中科院看出Foo类有两个实例属性,一目了然,写起来也比较简洁。
Class表达式
与函数一样,类也可以使用表达式的形式定义。
const MyClass = class Me{
getClassName(){
return Me.name;
}
}
代码使用表达式定义了一个类,但是,这个类的名字Me只能在Class内部使用,指代当前类,在Class外部,这个类只能用MyClass引用。
let inst = new MyClass();
inst.getClassName(); // Me
Me.name // // ReferenceError: Me is not defined
代码中,Me只在Class内部有定义。
如果类的内部没用到的话,可以省略Me。
const MyClass = class { /* .... */ }
采用Class表达式,可以写出立即执行的Class
let person = new class {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}('123');
person.sayName(); // 123
person是一个立即执行的类的实例。
注意
1. 严格模式
类和模块的内部,默认就是严格模式,所以不需要使用use strict指定运行模式。只要代码写在类或模块中,就只有严格模式可用。考虑到未来所有的代码,其实都是运行在模块之中,所以ES6实际上吧整个语言升级到了严格模式。
2. 不存在提升
类不存在变量提升,这个与ES5不同。
new Foo(); // ReferenceError
class Foo{}
代码中,Foo类使用在前,定义在后,这样会报错,因为ES6不会把类的声明提升到代码头部,必须保证子类在父类之后定义。
{
let Foo = class {}
class Bar extends Foo {}
}
代码不会报错,因为Bar 继承Foo的时候,Foo已经定义了,但是如果存在class提升,上面的代码就会报错,因为会被 提升到代码头部,而let命令是不会提升的,所以导致Bar继承Foo的时候,Foo还没有定义。
3. name属性
本质上,ES6的类只是ES5的构造函数的一层包装,所以函数的许多特性都被Class继承,包括name属性。
class Point {}
Point.name // 'Point'
name属性总是返回紧跟在class关键字后面的类名。
4. Generator 方法
如果某方法之前加上星号(*),就表示该方法是一个Generator函数。
class Foo {
constructor(...args){
this.args = args;
}
* [Symbol.iterator]() {
for(let arg of this.args){
yield arg;
}
}
}
for(let x of new Foo('hello', 'world')){
console.log(x);
}
// hello
// world
代码中,Foo类的Symbol.iterator方法前有一个星号,表示该方法是一个Generator函数。Symbol.iterator方法返回一个Foo类的默认遍历器,for…of循环会自动调用这个遍历器。
5. this的指向
类的方法内部如果含有this,它会默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。
class Logger{
printName(name = 'three'){
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; // this
箭头函数内部的this总是指向定义时所在的对象。上面代码中,箭头函数位于构造函数内部,它的定义生效是在构造函数执行的时候。这时,箭头函数所在的运行环境,肯定是实例对象,所以this会总是指向实例对象。
静态方法和静态属性
静态方法
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法钱,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就是‘静态方法’。
class Foo{
static classMethod(){
return '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(){
return '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'
静态属性
静态属性指的是Class本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性。
class Foo{
// ...
}
Foo.prop = 1;
Foo.prop // 1;
在Foo类定义了一个静态属性prop。
目前,只有这种写法可行,因为ES6明确规定,Class内部只有静态方法,没有静态属性,现在有一个提案提供了类的静态属性,写法是在实例属性的前面,加上static关键字。
class MyClass{
static myStaticProp = 42;
constructor(){
console.log(Myclass.myStaticProp) // 42
}
}
这个新写法大大方便了静态属性的表达。
// 老写法
class Foo {
// ...
}
Foo.prop = 1;
// 新写法
class Foo{
static prop = 1;
}
代码中,老写法的静态属性定义在类的外部,整个类生成以后,再生成静态属性。这样让人很容易忽略这个静态属性,也不符合相关代码应该放在一起的代码阻止原则。另外,新写法是显示声明,而不是赋值处理,语义更好。
Class继承
Class可以通过extends关键字实现继承,这比ES5的通过修改原型链实现继承,要清晰、方便很多。
class Point{}
class ColorPoint extends Point{}
代码定义了一个ColorPoint类,该类通过extends关键字,继承了Point类的所有属性和方法。但是由于没有部署任何代码,所以两个类完全一样,等于复制了一个Point类。
class ColorPoint extends Point{
constructor(x, y, color){
super(x, y); // 调用父类的constructor(x, y)
this.color = color;
}
toString(){
return this.color + ' ' + super.toString(); // 调用父类的toString()
}
}
代码中,constructor方法和toString方法之中,都出现了super关键字,它在这里表示父类的构造函数,用来新建父类的this对象。
子类必须在constructor方法中调用super方法,否则新建实例会报错。这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。如果不调用super方法,子类就得不到this对象。
class Point{/* ... */}
class ColorPoint extends Point {
constructor(){
// ....
}
}
let cp = new ColorPoint(); // ReferenceError
代码中,ColorPoint继承了父类的Point,但是它的构造函数没有调用super方法,倒是新建实例时报错。
ES5的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面(Parent.apply(this))。ES6的继承机制完全不同,实质是先将父类实例对象的属性和方法,加到this上面(所以必须先调用super方法),然后再用子类的构造函数修改this。
如果子类没有定义constructor方法,这个方法会被默认添加,不管有没有显式定义,任何一个子类都有constructor方法。
class ColorPoint extends Point{
// ...
}
// 等同于
class ColorPoint extends Point{
constructor(...args){
super(...args);
}
}
还有需要注意的地方是,在子类的构造函数中,只有调用super之后,才可以使用this关键字,否则会报错。这是因为子类实例的构建,基于父类实例,只有super方法才能调用父类实例。
class Point{
constructor(x, y){
this.x = x;
this.y = y;
}
}
class ColorPoint extends Point{
constructor(x, y, color){
this.color = color; // ReferenceErr
super(x, y);
this.color = color; // ok
}
}
代码中,子类的constructor方法没有调用super之前,就使用this关键字,结果报错,而放在super方法之后就是正确的。
下面是生成子类实例的代码。
let cp = new ColorPoint(2, 4, 'red');
cp instanceof ColorPoint // true
cp instanceof Point // true
代码中,实例对象cp同事是ColorPoint和Point两个类的实例,这与ES5的行为完全一致。
父类的静态方法,也会被子类继承。
class A {
static hello(){
console.log('hello world');
}
}
class B extends A {
// ...
}
B.hello(); // hello world
代码中,hello()是A类的静态方法,B继承A,也继承了A的静态方法。
Object.getPrototypeOf()
Object.getPrototypeOf方法可以用来从子类上获取父类。
Object.getPrototypeOf(ColorPoint) === Point // true
可以使用这个方法判断,一个类是否继承了另一个类。
super关键字
super这个关键字,既可以当做函数使用,也可以当做对象使用。
super作为函数
super作为函数调用时,代表父类的构造函数。ES6要求,子类的构造函数必须执行一次super函数。
class A{}
class B extends A{
constructor(){
super();
}
}
上面代码中,子类B的构造函数之中的super(), 代表调用父类的构造函数。
注意,super虽然代表了父类A的构造函数,但是返回的是子类B的实例,即super内部的this指的是B的实例,因此super()在这里相当于A.prototype.constructor.call(this)。
class A{
constructor(){
console.log(new.target.name);
}
}
class B extends A{
constructor(){
super();
}
}
new A(); // A
new B(); // B
代码中,new.target指向当前正在执行的函数,在super()执行时,它指向的是子类B的构造函数,而不是父类A的构造函数,所以说,super()内部的this指向的是B。
作为函数时,super()只能在子类的构造函数之中使用,用在其他地方就会报错。
class A {}
class B extends A{
my(){
super(); // 报错
}
}
代码中,super()用在B类的m方法之中,就会造成语法错误。
super作为对象
super作为函数时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类。
class A{
p(){
return 2;
}
}
class B extends A {
constructor(){
super();
console.log(super.p()); // 2
}
}
let b = new B();
代码中,子类B当中的super.p(),就是将super作为一个对象使用。这时,super在普通方法中,指向A.prototype,所以super.p()就相当于A.prototype.p()。
注意,由于super指向父类的原型对象,所以定义在父类实例上的方法和属性,是无法通过super调用的。
class A{
constructor(){
this.p = 2;
}
}
class B extends A{
get m(){
return super.p;
}
}
let b = new B();
b.m(); //undefined
代码中,p是父类A实例的属性,super.p就引用不到。
如果属性定义在父类的原型对象上,super就可以取到。
class A{}
A.prototype.x = 2;
class B extends A{
constructor(){
super();
console.log(super.x) // 2
}
}
let b = new B();
代码中,x是定义在A.prototype上的,所以super.x可以取到它的值。
ES6规定,在子类普通方法中通过super调用父类的方法时,方法内部的this指向当前的子类实例。
class A{
constructor(){
this.x = 2;
}
print(){
console.log(this.x);
}
}
class B extends A{
constructor(){
super();
this.x = 4;
}
m(){
super.print();
}
}
let b = new B();
b.m(); // 4
代码中,super.print()虽然调用的是A.prototype.print(),但是A.prototype.print()内部的this指向子类B的实例,导致输出的是4,不是2,实际上执行的是super.print.call(this).
由于this指向子类实例,所以如果通过super对属性赋值,这是super就是this,赋值的属性会变成子类实例的属性。
class A{
constructor(){
this.x = 1;
}
}
class B extends A{
constructor(){
super();
this.x = 2;
super.x = 3;
console.log(super.x); // undefined
console.log(this.x); // 3
}
}
let b = new B();
代码中,super.x赋值为3,这时等同于this.x赋值为3.而读取super.x的时候,读的是A.prototype.x,所以返回undefined。
如果super作为对象,用在静态方法之中,这是super将指向父类,而不是父类的原型对象。
class Parent{
static myMethod(msg){
console.log('static', msg);
}
myMethod(msg){
console.log('instance', msg);
}
}
class Child extends Parent{
static myMethod(msg){
super.myMethod(msg);
}
myMethod(msg){
super.myMethod(msg);
}
}
Child.myMethod(1); // static 1
var child = new Child();
child.myMthod(2); // instance 2
代码中,super在静态方法中指向父类,在普通方法中指向父类的原型对象。
另外,在子类的静态方法中通过super调用父类的方法时,方法内部的this指向当前的子类,而不是子类的实例。
class A{
constructor(){
this.x = 1;
}
static print(){
console.log(this.x);
}
}
class B extends A{
constructor(){
super();
this.x = 2;
}
static m(){
super.print();
}
}
B.x = 3;
B.m(); // 3
代码中,静态方法B.m里面,super.print指向父类的静态方法。这个方法里面的this指向B,而不是B的实例。
注意,使用super的时候,必须显示指定是作为函数,函数作为对象,否则会报错。
class A{}
class B extends A{
constructor(){
super();
console.log(super()); // 报错
}
}
代码中,console.log(super());中的super,无法看出是作为函数使用,还是作为对象使用,所以就是引擎解析代码的时候就会报错。这是,如果能清晰地表明super的数据类型,就不会报错。
class A{}
class B extends A{
constructor(){
super();
console.log(super().valueOf() instanceof B); // true
}
}
let b = new B();
上面代码中,super().valueOf()表明super是一个对象,因此不会报错。同事,由于super使得this指向B的实例,所以super().valueOf()返回的是一个B的实例。
由于对象总是继承其他对象的,所以可以在任意一个对象中,使用super关键字。
var obj = {
toString(){
return 'Myobj: ' + super.toString();
}
}
obj.toString(); // Myobj: [object Object]
类的prototype属性和__proto__属性
ES5中,每一个对象都有__proto__属性,指向对应的构造函数的prototype属性。
Class作为构造函数的语法糖,同时有prototype属性和__proto__属性,因此同时存在这两条继承连。
- 子类的__proto__属性,表示构造函数的继承,总是指向父类。
- 子类prototype属性的__proto__属性,表示方法的继承,总是指向父类的prototype属性。
class A{}
class B extends A{}
B.__proto__ === A; // true
B.prototype.__proto__ === A.prototype // true
代码中,子类B的__proto__属性指向父类A,子类B的prototype属性的__proto__属性指向父类A的prototype属性。
这样的结果是因为,类的继承是按照下面的模式实现的。
class A{}
class B{}
// B 的实例继承 A 的实例
Object.setPrototypeOf(B.prototype, A.prototype);
// B 继承 A 的静态属性
Object.setPrototypeOf(B, A);
const b = new B();
Object.setPrototypeOf()方法实现。
Object.setPrototypeOf = function (obj, proto) {
obj.__proto__ = proto;
return obj;
}
所以就有上面的结果。
Object.setPrototypeOf(B.prototype, A.prototype);
// 等同于
B.prototype.__proto__ = A.prototype;
Object.setPrototypeOf(B, A);
// 等同于
B.__proto__ = A;
这两条继承链,可以这样理解:作为一个对象,子类(B)的原型(__proto__属性)是父类(A);作为一个构造函数,子类(B)的原型对象(prototype属性)是父类的原型对象(prototype属性)的实例。
B.prototype = Object.create(A.prototype);
// 等同于
B.prototype.__proto__ = A.prototype;
extends关键字后面可以跟多种类型的值。
class B extends A {}
上面代码的A,只要是一个有prototype属性的函数,就能被B继承。由于函数都有prototype属性(除了Function.prototype函数),因此A可以是任意函数。
- 子类继承Object类
class A extends Object {}
A.__proto__ === Object // true
A.prototype.__proto__ === Object.prototype // true
这种情况下,A其实就是构造函数Object的复制,A的实例就是Object的实例。
- 不存在任何继承
class A {}
A.__proto__ === Function.prototype // true
A.prototype.__proto__ === Object.prototype // true
这种情况下,A作为一个基类(即不存在任何继承),就是一个普通函数,所以直接继承Function.prototype。但是,A调用后返回一个空对象(即Object实例),所以A.prototype.__proto__指向构造函数(Object)的prototype属性。
实例的__proto__属性
子类实例的__proto__属性的__proto__属性,指向父类实例的__proto__属性。也就是说,子类的原型的原型,是父类的原型。
var p1 = new Point(2, 3);
var p2 = new ColorPoint(2, 3, 'red');
p2.__proto__ === p1.__proto__ // false
p2.__proto__.__proto__ === p1.__proto__ // true
上面代码中,ColorPoint继承了Point,导致前者原型的原型是后者的原型。
因此,通过子类实例的__proto__.__proto__属性,可以修改父类实例的行为。
p2.__proto__.__proto__.printName = function () {
console.log('Ha');
};
p1.printName() // "Ha"
上面代码在ColorPoint的实例p2上向Point类添加方法,结果影响到了Point的实例p1。
new.target 属性
new是从构造函数生成实例对象的命令。ES6 为new命令引入了一个new.target属性,该属性一般用在构造函数之中,返回new命令作用于的那个构造函数。如果构造函数不是通过new命令或Reflect.construct()调用的,new.target会返回undefined,因此这个属性可以用来确定构造函数是怎么调用的。
function Person(name) {
if (new.target !== undefined) {
this.name = name;
} else {
throw new Error('必须使用 new 命令生成实例');
}
}
// 另一种写法
function Person(name) {
if (new.target === Person) {
this.name = name;
} else {
throw new Error('必须使用 new 命令生成实例');
}
}
var person = new Person('张三'); // 正确
var notAPerson = Person.call(person, '张三'); // 报错
上面代码确保构造函数只能通过new命令调用。
Class 内部调用new.target,返回当前 Class。
class Rectangle {
constructor(length, width) {
console.log(new.target === Rectangle);
this.length = length;
this.width = width;
}
}
var obj = new Rectangle(3, 4); // 输出 true
需要注意的是,子类继承父类时,new.target会返回子类。
class Rectangle {
constructor(length, width) {
console.log(new.target === Rectangle);
// ...
}
}
class Square extends Rectangle {
constructor(length, width) {
super(length, width);
}
}
var obj = new Square(3); // 输出 false
上面代码中,new.target会返回子类。
利用这个特点,可以写出不能独立使用、必须继承后才能使用的类。
class Shape {
constructor() {
if (new.target === Shape) {
throw new Error('本类不能实例化');
}
}
}
class Rectangle extends Shape {
constructor(length, width) {
super();
// ...
}
}
var x = new Shape(); // 报错
var y = new Rectangle(3, 4); // 正确
上面代码中,Shape类不能被实例化,只能用于继承。
注意,在函数外部,使用new.target会报错。