JavaScript-原型链理解总结

来源:妖精的尾巴
地址:https://www.jb51.net/article/224072.htm

1.理解:

原型:prototype 属性:只有函数对象具有,Object、Function、Array、RegExp、Date、Boolean、Number、String都是内置函数。prototype原型对象具有一个默认constructor属性

原型链:__ proto __ 属性:每个对象都有,__ proto __属性是一个对象,具有constructor 和 __ proto __ 两个属性

Object的原型对象(Object.prototype)的__proto__指向null,其他内置函数对象的原型对象(例如:Array.prototype)和自定义构造函数的 __proto__都指向Object.prototype, 因为原型对象本身是普通对象

()例子:(instanceof的手写实现:)

		function instance_Of(target, resource) {
						let r = resource.prototype 
						let t = target.__proto__
						 while(true) {
							 if (t === null) return false
							 if (r === t) return true
							 t = t.__proto__
						 }
					}
		console.log(instance_Of(new Map(),Map))//输出true
		console.log(instance_Of(new String('1'),String))//输出true
		console.log(instance_Of(new Number(1),String))//输出false

2.原型链和原型的意义:

增加不同子类的相同属性和方法,节省工作量,实现代码复用

例子:

	function persion(name,age) {
		this.name = name
		this.age = age
	}
	persion.prototype.motherland = 'china'
	let persion1 = new persion('01', 1)
	console.log(persion1)
	/*输出persion {name: '01', age: 1}
	age: 1
	haircolor: "green"
	name: "01"
	[[Prototype]]: Object
	eat: ƒ ()
	haircolor: "black"
	motherland: "china"
	constructor: ƒ persion(name,age)
	[[Prototype]]: Object
	*/
	let persion2 = new persion('02',2)
	persion.prototype.haircolor = 'black'
	persion.prototype.eat = function(){
		console.log("eat meat")
	}
	console.log(persion2)
	/*输出persion {name: '02', age: 2}
	age: 2
	name: "02"
	[[Prototype]]: Object
	eat: ƒ ()
	haircolor: "black"
	motherland: "china"
	constructor: ƒ persion(name,age)
	[[Prototype]]: Object
	*/
	persion1.haircolor = "green"
	console.log(persion1)
	/*输出persion {name: '01', age: 1, haircolor: 'green'}
	age: 1
	haircolor: "green"
	name: "01"
	[[Prototype]]: Object
	eat: ƒ ()
	haircolor: "black"
	motherland: "china"
	constructor: ƒ persion(name,age)
	[[Prototype]]: Object
	*/

你可能感兴趣的:(JavaScript总结,javascript)