原型链实现继承

// 赋值是给对象自身添加属性
// 获取属性会沿着原型链查找

/**
 * 参数使用借用构造函数,实现参数传递,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();

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值