原型和原型链是js中的难点也是重点,明白了原型和原型链会让我们在后面不管是学习还是工作都会更加高效,并且原型和原型链会是面试中必不可少的话题。
一,函数对象
所有引用类型(函数,数组,对象)都拥有__proto__属性(隐式原型)
所有函数拥有prototype属性(显式原型)(仅限函数)
原型对象:拥有prototype属性的对象,在定义函数时就被创建
二,构造函数
//创建构造函数
function Word(words){
this.words = words;
}
Word.prototype = {
alert(){
alert(this.words);
}
}
//创建实例
var w = new Word("hello world");
w.print = function(){
console.log(this.words);
console.log(this); //Person对象
}
w.print(); //hello world
w.alert(); //hello world
print()方法是w实例本身具有的方法,所以w.print()打印hello world;
alert()不属于w实例的方法,属于构造函数的方法,w.alert()也会打印hello world,因为实例继承构造函数的方法。
例w的隐式原型指向它构造函数的显式原型,指向的意思是恒等于
w.__proto__ === Word.prototype
三,原型和原型链
Function.prototype.a = "a";
Object.prototype.b = "b";
function Person(){}
console.log(Person); //function Person()
let p = new Person();
console.log(p); //Person {} 对象
console.log(p.a); //undefined
console.log(p.b);
想一想p.a打印结果为undefined,p.b结果为b
解析:
p是Person()的实例,是一个Person对象,它拥有一个属性值__proto__,并且__proto__是一个对象,包含两个属性值constructor和__proto__
console.log(p.__proto__.constructor); //function Person(){}
console.log(p.__proto__.__proto__); //对象{},拥有很多属性值
总结:
1.查找属性,如果本身没有,则会去__proto__中查找,也就是构造函数的显式原型中查找,如果构造函数中也没有该属性,因为构造函数也是对象,也有__proto__,那么会去它的显式原型中查找,一直到null,如果没有则返回undefined
2.p.__proto__.constructor == function Person(){}
3.p.___proto__.__proto__== Object.prototype
4.p.___proto__.__proto__.__proto__== Object.prototype.__proto__ == null
5.通过__proto__形成原型链而非protrotype