在ES6继承方式有多种,但存在一些弊端,这里介绍ES6之前终极继承方式
<script>
function Person(myName, myAge) {
this.name = myName;
this.age = myAge;
}
Person.prototype.say = function() {
console.log(this.name, this.age);
}
function Student(myName, myAge, myScore) {
Person.call(this, myName, myAge); //在子类的构造函数中通过call借助父类的构造函数,这里的this指的是Student
this.score = myScore;
this.study = function() {
console.log("day day up");
}
}
Student.prototype = new Person(); //将子类的原型对象修改为父类的实例对象
Student.prototype.constructor = Student;
Student.prototype.run = function() {
console.log("run");
}
let stu = new Student("ww", 19, 99);
console.log(stu.score);
stu.say();
stu.study();
</script>
控制台输出:
js中继承的终极方法
在子类的构造函数中通过call借助父类的构造函数
将子类的原型对象修改为父类的实例对象
从ES6开始,继承又是另外一种写法 关键词extends
<script>
class Person {
constructor(myName, myAge) {
this.name = myName;
this.age = myAge;
this.say = function() {
console.log("Hello World");
}
}
}
class Student extends Person {
constructor(myName, myAge, myScore) {
super(myName, myAge);
this.score = myScore;
this.study - function() {
console.log("day day up");
}
}
}
let p = new Student("Durant", 30, 100);
console.log(p);
</script>
控制台输出: