function Person(name, sex) {
this.name = name;
this.sex = sex;
}
Person.prototype.say = function () {
console.log(this.name + ' saying');
};
function Student(name, sex, no) {
// 借用构造函数传递增强子类实例属性(支持传参和避免篡改)
Person.call(this, name, sex);
this.no = no;
}
function inheritPrototype(subType, superType) {
const prototype = Object.create(superType.prototype); // 创建对象,创建父类原型的一个副本
prototype.constructor = subType; // 增强对象,弥补因重写原型而失去的默认的constructor 属性
subType.prototype = prototype; // 指定对象,将新创建的对象赋值给子类的原型
}
// 将父类原型指向子类
inheritPrototype(Student, Person);
Student.prototype.study = function () {
console.log(this.name + ' study');
};
const stu = new Student('coderxie', 'boy', 11002);
console.log(stu);
stu.say();
stu.study();
最后修改:2022 年 08 月 11 日 02 : 32 PM
© 允许规范转载