class类
ES5造类
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.sayName = function () {
return this.name
}
let p1 = new Person('张三', 28)
console.log(p1);
console.log(p1.sayName());
ES6造类
1.简单造类
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
sayName() {
return this.name
},
sayAge() {
return this.age
}
}
let p2 = new Person('张三', 28)
console.log(p2.sayName(),p2.sayAge(),p2.name,p2.age)
2.继承和父类方法的重写
继承(继承父类的属性和方法)
class Animal {
constructor(name, age) {
this.name = name
this.age = age
}
sayName() {
return this.name
}
sayAge() {
return this.age
}
}
class Dog extends Animal {
constructor(name, age, color) {
super(name, age)
this.color = color
}
sayColor() {
return `${this.name}今年${this.age}岁了,他是一条${this.color}色的狗`
}
sayName() {
return this.sayColor() + `这是重写的方法`
}
}
let dog = new Dog('小黄', 28, 'black')
console.log(dog.sayName(),dog.sayAge(),dog.name,dog.age);
3.get,set和Object.assign()
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
get name() {
console.log('价格属性被读取了');
return 'yes'
}
set name(newVal) {
console.log('价格属性被修改了');
}
}
let p2 = new Person('张三', 28)
Object.assign(Person.prototype, {
sayName() {
return this.name
},
sayAge() {
return this.age
}
})
console.log(p2.name);