JavaScript之类的使用

类Class

声明类

创建类

let Animal = function (type) {
  this.type = type
  this.eat = function () {
  	console.log('I am eat food')
  }
}
let dog = new Animal('dog')
let monkey = new Animal('Monkey')

如果eat方法是静态方法在初始化时会发生占用大量空间,所以我们将方法放入原型链中

Animal.prototype.eat = function () {
  console.log('I am eat food')
}

如果使用下面的方法,就只改dog的方法

dog.eat = function () {
  console.log('error')
}

用下面方法会更改所有该类的方法(方法要在原型链上)

dog.constructor.prototype.eat = function () {
  console.log('error')
}

ES6语法

class Animal {
  constructor (type) {
    this.type = type
  }

  eat () {
    console.log('I am eat food')
  }
}

let dog = new Animal('dog')
let monkey = new Animal('Monkey')

console.log(dog) //Animal {type: "dog"}
console.log(monkey)
dog.eat()
monkey.eat()

console.log(typeof Animal) // function

读写属性的保护

es6

let _age = 4
class Animal {
  constructor (type) {
    this.type = type
  }
  get age () {
    return _age
  }
  set age (val) {
    if (val < 7 && val > 4) {
      _age = val
    }
  }

  eat () {
    console.log('I am eat food')
  }
}
let dog = new Animal('dog')
console.log(dog.age)
dog.age = 6
console.log(dog.age)

静态方法和类方法

let Animal = function (type) {
  this.type = type
}

Animal.prototype.eat = function () {
  Animal.walk()
  console.log('i am eat food hello')
}

Animal.walk = function () {
  console.log('i am walk')
}

let dog = new Animal('dog')
dog.eat()

es6

class Animal {
  constructor (type) {
    this.type = type
  }
  eat () {
    Animal.walk()
    console.log('i am eat food')
  }
  static walk () { // 静态方法属于类的
    console.log('i am waling')
  }
}

let dog = new Animal('dog')
dog.eat()

静态方法不用调用实例的东西

继承

es5

let Animal = function (type) {
  this.type = type
}

let Dog = function () {
  // 初始化父类的构造函数
  Animal.call(this, 'dog')
  this.run = function () {
    console.log('i can run')
  }
}
// 引用
Dog.prototype = Animal.prototype

let dog = new Dog()
dog.run()
console.log(dog.type)

es6

class Animal {
  constructor (type) {
    this.type = type
  }
  eat () {
    Animal.walk()
    console.log('i am eat food')
  }
  static walk () { // 静态方法属于类的
    console.log('i am waling')
  }
}

class Dog extends Animal {
  constructor (type) {
    super('dog')// 不管如何参数要与父类的一样
    this.age = 2
  }
}
let dog = new Dog()
dog.eat()
console.log(dog.type)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值