原型繼承
子類型的原型為父類型的一個實例對象
function Person (name, age) {
this.name = name;
this.age = age;
}
Person.prototype.setName = function (name) {
this.name = name;
}
function Student (name, age, grade) {
Person.call(this, name, age);
this.grade = grade;
}
// 子類型的原型為父類型的一個實例對象
function F () {}
F.prototype = Person.prototype;
Student.prototype = new F();
// 修復(fù)子類型的 constructor 指向
Student.prototype.constructor = Student;
Student.prototype.setGrade = function (grade) {
this.grade = grade;
}
var st1 = new Student('aaa', 18, 88);
console.log(st1); // Student { name: 'aaa', age: 18, grade: 88 }
st1.setGrade(90);
st1.setName('bbb');
console.log(st1); // Student { name: 'bbb', age: 18, grade: 90 }
繼承封裝
function inherit(Target, Origin) {
function F() {};
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
}
function inherit(Target, Origin) {
Target.prototype = Object.create(Origin.prototype);
Target.prototype.constructor = Target;
}
class
class Person {
constructor (name, age) {
this.name = name;
this.age = age;
}
getName () {
console.log(this.name);
}
}
let person = new Person('aaa', 18);
等同于
function Person (name, age) {
this.name = name;
this.age = age;
}
Person.prototype.getName = function (name) {
console.log(this.name);
}
let person = new Person('aaa', 18);
class 繼承
// Person 類
class Person {
constructor (name, age) {
this.name = name;
this.age = age;
}
setName (name) {
this.name = name;
}
}
// Student 類繼承自 Person 類
class Student extends Person {
constructor (name, age, grade) {
super(name, age); // 調(diào)用父類的構(gòu)造方法
this.grade = grade;
}
setGrade (grade) {
this.grade = grade;
}
}
let st1 = new Student('aaa', 18, 80);
console.log(st1); // Student { name: 'aaa', age: 18, grade: 80 }
st1.setName('bbb');
st1.setGrade(90);
console.log(st1); // Student { name: 'bbb', age: 18, grade: 90 }