构造函数
function M(x, y) {
this.x = x
this.y = y
}
M.prototype.add = function () {
return this.x + this.y
}
let m = new M(5, 6)
console.log(m.add())
Class构造函数
class M {
constructor(x, y) {
this.x = x
this.y = y
}
add () {
return this.x + this.y
}
}
const m = new M(5, 6)
console.log(m.add())
class的本质还是函数
class M {
constructor(x, y) {
this.x = x
this.y = y
}
add () {
return this.x + this.y
}
}
const m = new M(5, 6)
console.log(typeof M) //funtion
console.log(M.prototype.constructor === M) //true
console.log(m.__proto__ === M.prototype) //true
Class 继承
class Animal {
constructor(name) {
this.name = name
}
eat () {
console.log(this.name + 'eat')
}
}
class Dog extends Animal {
constructor (name) {
super(name) // 必须写上
this.name = name
}
say () {
console.log(this.name + 'say')
}
}
let dog = new Dog('哈士奇')
dog.say() //哈士奇say
dog.eat() //哈士奇eat
总结
- class更加贴近于面向对象的写法
- class 实现继承更加简单易懂,易理解
- 本质还是语法糖,使用prototype
网友评论