FIG prototype chain
Master this picture, do not read the following
Concepts
js objects with _proto_
attributes, it points to the object prototype, the prototype object prototype object has been up until Object.prototype
, until null,
the object itself is not a property or method, will always looking up prototype object along the chain, untilObject.prototype
js is also a function of the object, there is also a _proto_
property, point to Function.prototype
, Function.prototype._proto_
is the Object.prototype
addition when the function as a constructor, but also a unique prototype
attribute point to an instance it creates a prototype object, the prototype property of the object construstor
and point to this function
function Function(){}
It is a special function, which is itself constructor, the F._proto_
point F.prototype
, F.prototype.constructor
point F
//构造函数 Person
function Person(name){
this.name = name
}
//构造函数通过 new 生成实例
var p = new Person("tom");
//p 的 _proto_ 指向它的原型对象,即 Person.prototype
console.log(p.__proto__ === Person.prototype) // true
//原型对象的 constructor 属性指向实例的构造函数
console.log(Person.prototype.constructor === Person) // true
//p 的原型对象的构造函数是 Object,所以原型对象的原型对象是 Object.prototype
Person.prototype._proto_ === Object.prototype //true
//Object.prototype 再向上找原型对象就是 null
Object.prototype._proto_ === null //true
//在 p 的原型对象上添加属性 age
Person.prototype.age = 18;
//在 Object.prototype 上添加方法 sayHi
Object.prototype.sayHi = function (){console.log("hi")}
// p 自身只有一个 name 属性,并无 age 属性和 sayHi 方法
console.log(p) // {name:"tom"}
//p 自身没有 age 属性,会自动向 p 的原型对象上寻找 age 属性,找到,则停止向上找
console.log(p.age) // name, 18
//p自身没有 sayHi 方法,p 的原型对象上也没有,则继续向上找,找到了 Object.prototype,找到了 sayHi
p.sayHi() // hi