JS中构造函数与类
Function vs Class
写法上有区别,本质上无差别
class Clz {
a() {}
b() {}
}
Class的数据类型:
typeof Clz; // 'function'
Class对象本身:
Clz === Clz.prototype.constructor; // true
需要注意的隐晦差异:
function Clzf() {}
Clzf.prototype.a = function() {};
Clzf.prototype.b = function() {};
Class内部定义的方法是不可枚举的,但通过构造函数定义的方法是可枚举的。
Object.keys(Clz.prototype); // []
Object.keys(Clzf.prototype); // ['a', 'b']
关于 new.target 属性
该属性可以用来检测是否是使用 new 运算符调用的构造方法或者函数。
通过使用 new 运算法,new.target会返回一个指向构造方法或函数的引用。
普通函数调用,new.target的返回值为undefined.
function Foo() {
if (new.target === undefined) {
throw new Error('Foo() must be called with new');
}
console.log('Foo instantiated with new.');
}
Foo(); // 报错
new Foo(); // Foo instantiated with new.
class A {
constructor() {
console.log(new.target.name);
}
}
class B extends A {
constructor() {
super();
}
}
const a = new A(); // 'A'
const b = new B(); // 'B'