原型
了解原型链,我们先了解下原型
- 所有的对象都有toString()、valueOf()、constructor、hasOwnProperty()等
- 所有的数组都是有对象应该有的属性
- 所有的数组都有push()、shift()、join()、slice()、splice()等
- var array = [] 应该有数组共有的所有属性
1 | var array = [] |
我们用console.dir()检测下array有什么属性

我们发现 console.dir(array) 打出来的结果是:
- array 有一个属性叫做
__proto__(它是一个对象) array.__proto__有很多属性,包括 push()、shift()、join()、slice()、splice()等array.__proto__其实也有一个叫做__proto__的属性,包括toString()、valueOf()、constructor、hasOwnProperty()等array.__proto__.__proto__其实也有一个叫做__proto__的属性(console.log 没有显示),值为 null
原型链
当我们读取 array.toString 时,JS 引擎会做下面的事情:
看看 array 数组本身有没有 toString 属性。没有就走到下一步。
看看
array.__proto__有没有 toString 属性,发现array.__proto__有 toString 属性,于是找到了
所以 array.toString 实际上就是第 2 步中找到的 array.__proto__.toString。
可以想象,
如果
array.__proto__没有,那么浏览器会继续查看array.__proto__.__proto__如果
array.__proto__.__proto__也没有,那么浏览器会继续查看array.__proto__.__proto__.__proto__直到找到 toString 或者
__proto__为 null。
上面这个搜索过程,是连着由__proto__ 组成的链子一直走的。
这个链子,就叫做原型链。

API
hasOwnProperty() 方法
hasOwnProperty() 方法会返回一个布尔值,指示对象是否具有指定的属性作为自身(不继承)属性。
1 | var o = { |
2 | name:'jack' |
3 | } |
4 | o.hasOwnProperty('name'); // true |
5 | o.hasOwnProperty('toString'); // false |
Object.create() 方法
Object.create() 方法使用指定的原型对象和其属性创建了一个新的对象。
1 | var a ={ |
2 | name:'jack' |
3 | } |
4 | var b = { |
5 | form:'china' |
6 | } |
7 | a = Object.create(b) |

prototype
对象.__proto__ === 对象.constructor.prototype
1 | function Person(){} |
2 | Person.prototype.name = 'jack' |
3 | var person= new Person() |
4 | console.log(person.name) // jack |
5 | console.log(person.__proto__ === Person.prototype) // true |
6 | console.log(Person.__proto__ === Person.constructor.prototype) // true |
7 | console.log(Person.__proto__ === Function.prototype) //true |
8 | console.log(Person.prototype.constructor === Person) // true |
9 | console.log(Object.prototype.__proto__ === null) // true |
10 | console.log(Object.prototype.constructor === Object) // true |
11 | console.log(person.constructor === Person) // true |
12 | console.log(person.constructor === Person.prototype.constructor) // true |

只有对象才有__proto__,只有函数才有 prototype。