原型链(三句话搞定原型链)

418 阅读1分钟


首先:图上的三列分别表示实例、构造函数、原型对象。

1、实例:通过构造函数new出来的一个对象。

      

function Person(name){
    this.name=name
}
var person1=new Person("nanxin") //这里的 person1 就是实例

2、构造函数:常常用大写字母开头,比如  function Person()

function Person(name){
    this.name=name
}

3、原型对象:也就是prototype对象。

比如:Object.prototype      Function.prototype    Person.Prototype
这些都是本文中所说的的prototype对象。


那三句话是什么呢?

一、每个实例的__proto__指向该实例构造函数的prototype对象。

//栗子1:
function Person(name){
    this.name=name
}
var person1=new Person("nanxin")

//因为person1的构造函数是 Person,所以
person1.__proto__===Person.prototype  //true

二、构造函数也属于函数,所以构造函数的__proto__指向Function.prototype。

//栗子2:
function Person(name){
    this.name=name
}

Person.__proto__===Function.prototype //true


//栗子3:
//Function也是构造函数,是不是超级神奇!
Function.__proto__===Function.prototype   //true
//记住这口诀,你就无敌了!

三、原型对象本质上也是对象,属于Object的实例,所以原型对象的__proto__指向Object.prototype。(除了Object.prototype.__proto__===null)

//栗子4:
Function.prototype.__proto__===Object.prototype   //true

//栗子5:
function Person(name){
    this.name=name
}
Person.prototype.__proto__===Object.prototype   //true

最后就是Object.prototype的__proto__指向null。这是特例。

Object.prototype.__proto__===null  //true

说的很精简,但是记住这三句对我们学习原型链真的很有帮助!

有问题欢迎留言!