javascript 类的本质

1,399 阅读1分钟

1.ES6 之前我们通过 构造函数 + 原型 实现面向对象编程。

(1)构造函数的一些特征

  • 构造函数有原型对象 prototype。
  • 构造函数原型对象里面有 prototype 里面有 constructor 指向构造函数本身。
  • 构造函数可以通过原型对象添加方法。
  • 构造函数创建的实例对象有 _proto_ 原型指向 构造函数的原型对象。

2.ES6 通过 类 实现面向对象编程

  • class 其实类的本质还是一个 function。
  • 类的所有方法都定义在了 prototype 属性上。
  • 类创建的实例,里面也有 _proto_ 指向类的 prototype 原型对象。
  • 所以 ES6 类他的绝大部分功能, ES5 都可以做到,新的 class 写法只是让对象原型的写法更清晰,更像面向对象编程的语法而已。
  • ES6 中的 class 其实就是一个语法糖。

(1) 我们可以简单的认为类就是构造函数的另一种写法。

class Star{
    
}
console.log(typeof Star)

打印结果:

(2)看看类有没有构造函数的特征

(1)原型对象 prototype
function Star1(){

    }
    class Star2{

    }
    console.log(Star1.prototype)
    console.log(Star2.prototype)

打印结果:

(2)constructor 构造函数指回本身

function Star1(){

}
class Star2{

}
console.log(Star1.prototype.constructor)
console.log(Star2.prototype.constructor)

打印结果:

(3)通过原型对象添加方法

function Star1(){

}
Star1.prototype.sing = function (){
    console.log('喝水')
}
class Star2{

}
Star2.prototype.sing = function (){
    console.log('喝水')
}
let star1 = new Star1
let star2 = new Star2
console.log(star1)
console.log(star2)

(4)构造函数创建的实例对象有 _proto_ 原型指向 构造函数的原型对象。

function Star1(){

}
Star1.prototype.sing = function (){
    console.log('喝水')
}
class Star2{

}
Star2.prototype.sing = function (){
    console.log('喝水')
}
let star1 = new Star1
let star2 = new Star2
console.log(star1.__proto__ === Star1.prototype)
console.log(star2.__proto__ === Star2.prototype)

打印结果: