ES6
class Example {
constructor(name) {
this.name = name;
}
init() {
const fun = () => {
console.log(this.name);
};
fun();
}
}
const e = new Example('Hello');
e.init();
ES5
四个注意的点
- ES6的class必须通过new来调用
- ES6的class中的所有代码均处于严格模式下
- ES6中,原型上的方法不可枚举
- 原型上的方法不可通过new调用
function Example(name){
'use strict'
if(!new.target){
throw new Error("Class constructor cannot be invoked without new");
}
this.name = name
}
Object.defineProrperty(Example.prototype, "init", {
enumerable: false;
value: function(){
'use strict'
if(new.target){
throw new Error("init is not a contructor");
}
var fun = function(){
console.log(this.name);
}
fun.call(this);
}
})
手撕代码系列