类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)