原型链

原型

了解原型链,我们先了解下原型

  1. 所有的对象都有toString()、valueOf()、constructor、hasOwnProperty()等
  2. 所有的数组都是有对象应该有的属性
  3. 所有的数组都有push()、shift()、join()、slice()、splice()等
  4. var array = [] 应该有数组共有的所有属性
var array = []

我们用console.dir()检测下array有什么属性

我们发现 console.dir(array) 打出来的结果是:

  1. array 有一个属性叫做 __proto__(它是一个对象)
  2. array.__proto__ 有很多属性,包括 push()、shift()、join()、slice()、splice()等
  3. array.__proto__其实也有一个叫做 __proto__的属性,包括toString()、valueOf()、constructor、hasOwnProperty()等
  4. array.__proto__.__proto__ 其实也有一个叫做 __proto__的属性(console.log 没有显示),值为 null

原型链

当我们读取 array.toString 时,JS 引擎会做下面的事情:

  1. 看看 array 数组本身有没有 toString 属性。没有就走到下一步。

  2. 看看 array.__proto__有没有 toString 属性,发现 array.__proto__有 toString 属性,于是找到了

所以 array.toString 实际上就是第 2 步中找到的 array.__proto__.toString

可以想象,

  1. 如果 array.__proto__ 没有,那么浏览器会继续查看 array.__proto__.__proto__

  2. 如果 array.__proto__.__proto__ 也没有,那么浏览器会继续查看 array.__proto__.__proto__.__proto__

  3. 直到找到 toString 或者 __proto__为 null。

上面这个搜索过程,是连着由 __proto__ 组成的链子一直走的。

这个链子,就叫做原型链。

API

hasOwnProperty() 方法

hasOwnProperty() 方法会返回一个布尔值,指示对象是否具有指定的属性作为自身(不继承)属性。

var o = {
  name:'jack'
}
o.hasOwnProperty('name'); // true
o.hasOwnProperty('toString'); // false

Object.create() 方法

Object.create() 方法使用指定的原型对象和其属性创建了一个新的对象。

var a ={
  name:'jack'
}
var b = {
  form:'china'
}
a = Object.create(b)

prototype

对象.__proto__ === 对象.constructor.prototype

function Person(){}
Person.prototype.name = 'jack'
var person= new Person()
console.log(person.name)  // jack
console.log(person.__proto__ === Person.prototype) // true
console.log(Person.__proto__ === Person.constructor.prototype) // true
console.log(Person.__proto__ === Function.prototype) //true
console.log(Person.prototype.constructor === Person) // true
console.log(Object.prototype.__proto__ === null) // true
console.log(Object.prototype.constructor === Object) // true
console.log(person.constructor === Person) // true
console.log(person.constructor === Person.prototype.constructor) // true

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容