JavaScript ES6中的继承
<script>
/*
// ES6之前的继承
function Person(myName, myAge) {
this.name = myName;
this.age = myAge;
this.say = function () {
console.log(this.name, this.age);
};
}
function Studnt(myName, myAge, myScore) {
// 通过call函数借用父类的构造函数
Person.call(this, myName, myAge);
this.score = myScore;
this.learn = function () {
console.log("day day up");
};
}
// 将子类的原型对象更改为父类的实例对象
Studnt.prototype = new Person();
Studnt.prototype.constructor = Studnt;
let stu = new Studnt("peter", 20, 50);
stu.say();
console.log(stu);
*/
// ES6中的继承
class Person{
constructor(myName, myAge){
this.name = myName;
this.age = myAge;
}
say(){
console.log(this.name, this.age);
}
}
class Student extends Person{
constructor(myName, myAge, myScore){
super(myName, myAge);
this.score = myScore;
}
learn = function(){
console.log("day day up");
}
}
let stu = new Student("tm", 12, 100);
console.log(stu);
stu.say();
</script>
作者:陈太浪
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。