class转function

65 阅读1分钟

类:

class Person{
    constructor(name){
        this.name = name
    }
    fun(){
        console.log(this.name);
    }
}

function:

  • 添加严格模式use strict
  • class声明的类要用new构造 new.target判断
  • class中属性不可枚举definePropertyenumerable
  • class中的方法不能new new.target
//class中的代码处于严格模式
'use strict'

function Person(name){
    //class后面的如Person要用new调用,不用new调用就报错
    if(!new.target){
        throw new error('要用new构造')
    }
    this.name = name;
}
//class中属性是不可枚举的
Object.defineProperty(Person.prototype,'fun',{
    value:function(){
        //不能使用new来调用比如new Person.prototype.fun()
        if(new.target){
            throw new error('这里不能用new调用')
        }
        console.log(this.name);
    },
    //设置不可枚举
    enumerable:false
})
//原来的添加原型链写法
// Person.prototype.fun = function(){
//     console.log(this.name);
// }