// 赋值是给对象自身添加属性
// 获取属性会沿着原型链查找
/**
* 参数使用借用构造函数,实现参数传递,Person.call(this, name, age);
* 直接new Person()的缺点:
* 1: Person被调用了两次
* 2:new Person() 创建的对象上也会有一份属性
*
* */
function createObj(o) {
function Fn() {}
Fn.prototype = o;
return new Fn();
}
function inheritPrototype(subType, superType) {
subType.prototype = createObj(superType.prototype);
Object.defineProperty(subType.prototype, "constructor", {
enumerable: false,
configurable: true,
writable: true,
value: subType,
});
}
// 父类:公共的属性和方法
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.runing = function () {
console.log("runing");
};
Person.prototype.eating = function () {
console.log("eating");
};
// 子类: 私有的属性和方法
function Student(name, age, sno) {
Person.call(this, name, age);
this.sno = sno;
}
inheritPrototype(Student, Person);
// Student.prototype = new Person();
Student.prototype.studing = function () {
console.log("studing");
};
const stu = new Student("why", 18, 11);
console.log(stu);
stu.eating();
stu.studing();
原型链实现继承
最新推荐文章于 2024-09-30 15:23:15 发布