js中的类

ES5 prototype

function Dog(name){
  this.name = name
  this.legs = 4
}
Dog.prototype.say = function(){
  console.log(`${this.name} - ${this.legs}`)
}
Dog.prototype.kind = '狗'

const d1 = new Dog('tom')
const d2 = new Dog('jimmy')
d1.say()
d2.say()

在prototype中放置可共享的属性(避免内存浪费),在函数中放置各自的私有属性

ES6 class

class Dog {
  kind = '狗'
  constructor(name){
    this.name = name
    this.legs = 4
  }
  say(){
  }
  run(){
  }
}
const d1 = new Dog('jimmy')
d1.say()

js原型链继承的实现

function Animal(legsNumber){
  this.legsNumber = legsNumber
}
Animal.prototype.kind = '动物'
function Dog(name){
  Animal.call(this,4) // this.legsNumber = 4
  this.name = name
}
// Dog.prototype.__proto__ = Animal.prototype 不是所有浏览器都存在__proto__属性
var emptyAnimal = function(){}
emptyAnimal.prototype = Animal.prototype
Dog.prototype = new emptyAnimal()
Dog.prototype.say = function(){
  console.log(`${this.name} - ${this.legs}`)
}
Dog.prototype.kind = '狗'

new的作用:

  1. 创建临时对象
  2. this = 临时对象
  3. 'this.proto' = 构造函数的prototype
  4. 执行构造函数
  5. return this

我们希望执行上面的1,2,3,5,因为4在我们声明Dog时已经使用,所以我们需要构建一个空的函数体的emptyAnimal,然后我们执行Dog.prototype = new emptyAnimal()就能完成继承

es6 class 继承

class Animal {
  constructor(legsNumber){
    this.legsNumber = legsNumber
  }
  run(){}
}
class Dog extends Animal{
  constructor(name){
    super(4)
    this.name = name
  }
  say(){
    console.log(`${this.name} ${this.legsNumber}`)
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 如何定义一个类 ES5中定义一个类: ES6以后的语法(可以看做是ES5的语法糖): ES6的类,完全可以看作构造...
    西瓜鱼仔阅读 180评论 0 1
  • ES5 中定义一个类 ES6以后的语法(可以看做是ES5的语法糖) ES6 的类,完全可以看作构造函数的另一种写法...
    施主画个猿阅读 19,632评论 0 5
  • ES5中,使用构造函数是这样的: ES6中,构造函数 上面中constructor就是构造方法。注意定义类的方法时...
    柒轩轩轩轩阅读 292评论 0 1
  • 前言 JavaScript在ES6之前严格意义上是没有像JAVA,C#这种语言中类的概念的。ES6添加了class...
    Harlan_Zhang阅读 230评论 0 0
  • 什么是Class 类? MDN上说:类定义对象的特征。它是对象的属性和方法的模板定义。简单说,“类”是生产对象的模...
    饥人谷_风争阅读 873评论 0 3