js构造函数继承

//寄生式继承:对象继承对象
function createObject(o) {
	function Fn() {}
	Fn.prototype = o;
	return new Fn();
}

function inheritPrototype(SubType, SuperType) {
	/**社区的写法,因为Object.create比较新
	 SubType.prototype = createObject(SuperType.prototype);
	 */
	SubType.prototype = Object.create(SuperType.prototype);

//创建的对象,没有constructor,所以没有类的name属性,所以采用下面的绑定
	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.eating = function () {
	console.log(this.name + '在吃东西');
};

function Student(name, age, sno) {
	Person.call(this, name, age); //属性的继承
	this.sno = sno;
}
inheritPrototype(Student, Person);
/**
 * 方法的继承,创建一个新的对象
 * Stuent.prototype--->obj;
 * obj.__proto__---->Person.prototype
 *
 */

Student.prototype.studying = function () {
	console.log(this.name + '在学习');
};

const s1 = new Student('mike', 18, 11111);
console.log(s1);

s1.eating();
s1.studying();

posted @ 2021-12-03 08:59  Wayhome'  阅读(103)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css