0
点赞
收藏
分享

微信扫一扫

js类的封装和继承

//ES6之前没有class类的定义都是通过构造函数 call实现类的继承
function Animal(name, age) {
this.name = name;
this.age = age
}
Animal.prototype.eat = function() {
console.log("animal eat")
}

function Dog(name, age, sex) {
Animal.call(this, name, age)

this.sex = sex
}
Dog.prototype = new Animal()
Dog.prototype.constructor = Dog
var dog = new Dog("dd", 12, "w")
console.log(dog)

  

//ES6类封装 constructor中this指向类new实例对象 方法中的this指向这个方法的调用者
class Star {
constructor(name) {
this.name = name;
this.btn = document.querySelector('button');
this.btn.onclick = this.click
}
click() {
console.log(this, this.name)//此时this是button
}
sing(song) {
console.log(this.name + " sing " + song)
}
show(movie) {
console.log(this.name + " show " + movie)
}
}
var zxy = new Star("张学友")
var ldh = new Star("刘德华")
zxy.sing("一千个伤心的理由")
ldh.sing('冰雨')
//es6类继承
class Animal {
constructor(name) {
this.name = name
}
eat() {
console.log(this.name + ' eat')
}
}
class Dog extends Animal {

}
var dog = new Dog('dog')
dog.eat()

class Calc {
constructor(x, y) {
this.x = x;
this.y = y
}
sum() {
console.log(this.x + this.y)
}
}
class Add extends Calc {
constructor(x, y) {
super(x, y)
}
add() {
console.log(this.x + this.y)
}
}
var add1 = new Add()
add1.sum()
add1.add()

  


举报

相关推荐

0 条评论