ES6 的 class 和 普通构造函数的区别
-
ES6 中的 class 必须通过 new 来调用,不能当作普通函数调用,否则报错。(因此,在答案中,加入了 'new.target' 来判断调用方式。)
-
ES6 中的 calss 中所有代码均处于严格模式下。(因此,在答案中,无论是构造函数本身还是原型方法,都使用了严格模式。)
-
ES6 中的原型方法是不可被枚举的。(因此,在答案中,定义原型方法使用了属性描述符,让其不可枚举。)
-
原型上的方法不允许通过 'new' 来调用。(因此,在答案中,原型方法中加入 "new.target" 来判断调用方式。)
// ES6
class Example {
constructor(name) {
this.name = name;
}
init() {
const fun = () => { console.log(this.name) }
fun();
}
}
const e = new Example('Hello');
e.init();
// ES5
function Example(name) {
'use strict';
if(! new.target) {
throw new TypeError('Class constructor cannot be invoted without new')
}
this.name = name;
}
Object.defineProperty(Example.prototype, 'init', {
enumerable: false,
value: function(){
'use strict';
if(new.target){
throw new TypeError('init is not a constructor');
}
var fun = function() {
console.log(this.name);
}
fun.call(this)
}
})