面试官: class和普通构造函数有什么区别

238 阅读1分钟

JS构造函数

//js构造函数语法:
function Mathandle(x,y){
    this.x = x
    this.y = y
}
//通过 继承Mathandle的函数,使用里面的值
Mathandle.prototype.add=function(){
    return this.x + this.y 
}
var m = new Mathandle(1,2)
console.log(m.add())

//class语法:
class MathHandle{
    constructor(x,y){
        this.x = x
        this y = y
    }
    add(){
        return this.x + this.y
    }
}
const m = new MathHandle(2,3)
console.log(m.add())

语法糖:

在上述两段代码中分别加入一下代码,运行

console.log(typeof MathHandle)   //function
console.log(Mathhandle.prototype.constructor === MathHandle)  //true
console.log(m.__proto__ === MathHandle.prototype)  //true

**执行结果完毕后,运行结果一致的时候,我就认为,class是构造函数的语法糖

从上面来看:

  • Class在语法上更加贴合面向对象的写法
  • Class实现继承更加容易读,容易理解,更易于写Java,等后端语言的使用,
  • 但是本质还是语法糖