原型链&js的继承

168 阅读1分钟

看了些其他人写的,还有画的图,感觉还是无法直观理解,还是直接看输出吧,反正就两个属性prototype跟__proto__

function male (name, age) {
		this.name = name;
		this.age = age;
	}
	male.prototype.sex = 'male';
	male.prototype.getValue = function () {
		console.log('getValue:' + this.sex)
	}
	console.log('1 male.__proto__(): ' + male.__proto__());	// undefined  不存在
	console.log('2 male.__proto__:' + male.__proto__);		// function () { [native code] }
	console.log('2.1 constructor:' + male.constructor)		// 同上
	var person1 = new male('li', 13);
	// person1.__proto__.sex = 'sprot';
	var person2 = new male('wang', 32);
	console.log('3 person1: ' + JSON.stringify( person1));	// {"name":"li","age":13}
	console.log('4 person2: ' + person2);					// [object Object]
	
	console.log('5 person1.prototype: ' + person1.prototype);			// undefined
	// console.log('6 person1.__proto__(): ' + person1.__proto__());	// is not a function
	console.log('7.1 person1.sex:' + person1.sex);
	console.log('7 person1.__proto__: ' + person1.__proto__);			// [object Object] {'sex': 'male'} 指向下行中的male.prototype
	console.log('8 male.prototype: ' + JSON.stringify(male.prototype));	// {'sex': 'male'}	
	
	// 继承另一种写法
	function person (arg1, arg2) {
		male.call(this, arg1, arg2)
	}
	person.prototype = new male();
	const person3 = new person('mac', '11');
	person3.getValue()
	console.log('9 person3 instanceof male: ' + (person3 instanceof male));
	console.log('9.1 person1 instanceof  male:' + (person1 instanceof  male));

es6中的继承用起来更爽一些,像极了java,但底层还是基于原型链实现的。

class Parents {
	constructor (name, age) {
		this.name = name;
		this.age = age;
	}
	show () {
		console.log('I am ' + this.name + ',' + this.age + ' years old.');
	}
};
class Child extends Parents {
	// 构造函数重写
	constructor (name, age, sex) {
		super(name, age);
		this.sex = sex;
	}
	// 还可以重写show
	show () {
		console.log(this.name + '==' + this.age + '==' + this.sex);
	}
};
class Child2 extends Parents {}
let child = new Child('mac', 18, 'male');
child.show();
let child2 = new Child2('child', 7);
child2.show();

仅作为个人学习、阅读笔记,如有不足之处请指教,如有侵权请联系本人即删除