美文网首页
js中的类

js中的类

作者: 西域战神 | 来源:发表于2022-05-31 20:55 被阅读0次

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}`)
  }
}

相关文章

  • Js 中的类

    ES5中,使用构造函数是这样的: ES6中,构造函数 上面中constructor就是构造方法。注意定义类的方法时...

  • js 中的类

    ES5 中定义一个类 ES6以后的语法(可以看做是ES5的语法糖) ES6 的类,完全可以看作构造函数的另一种写法...

  • JS中的类

  • JS中的类

    如何定义一个类 ES5中定义一个类: ES6以后的语法(可以看做是ES5的语法糖): ES6的类,完全可以看作构造...

  • js中的类

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

  • js给元素添加类的方法

    原生js中添加类的方法 .jquery中添加类的方法 检查是否含有某个类的方法 例子:html部分 css部分 js部分

  • js的封装

    JS的封装(JS插件的封装) JS中类的概念 类,实际上就是一个function,同时也是这个类的构造方法,new...

  • 在Java中调用JS方法

    在Java中调用JS方法 供JS调用的接口类

  • QML 中实现类似 Intl.NumberFormat 的功能

    Intl.NumberFormat 是 JS 中对语言敏感的格式化数字类的构造器类,JS 的语法: QML 中是没...

  • ES6-面向对象

    1、区别 es5(js)中没有一个类的概念,只有构造方法在es6中 js模拟了其他语言实现类的概念,让对象可以由类...

网友评论

      本文标题:js中的类

      本文链接:https://www.haomeiwen.com/subject/ructmrtx.html