ES5 如何声明一个类
let Animal = function (type) {
// 属性
this.type = type
}
// 原型链上挂载方法做继承
Animal.prototype.eat = function () {
console.log('i am eat food hello')
}
let dog = new Animal('dog')
let monkey = new Animal('monkey')
console.log(dog)
console.log(monkey)
// 修改原型链上继承的方法
monkey.constructor.prototype.eat = function () {
console.log('error')
}
dog.eat()
monkey.eat()
ES6 如何声明一个类,class只是语法糖,本质和ES5的声明类是一致的
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)
console.log(monkey)
dog.eat()
monkey.eat()
// 判断类型 function
console.log(typeof Animal)
属性 私有属性 只读
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 = 8
console.log(dog.age)
console.log(dog._age)
ES5 类的静态方法和实例对象方法
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 walking')
}
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 walking')
}
}
let dog = new Animal('dog')
dog.eat()
let Animal = function (type) {
this.type = type
}
// ES5 中继承
Animal.prototype.eat = function () {
Animal.walk()
console.log('i am eat food hello')
}
Animal.walk = function () {
console.log('i am walking')
}
let Dog = function () {
// 初始化父类的构造函数,改变this的指向,animal的this指向dog的实例
Animal.call(this, 'dog')
this.run = function () {
console.log('i can run')
}
}
// 值类型,引用类型
Dog.prototype = Animal.prototype
let dog = new Dog('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 walking')
}
}
class Dog extends Animal {
// 显式,隐式
constructor (type) {
super(type)
this.age = 2
}
}
let dog = new Dog('dog')
dog.eat()
学习视频记录
网友评论