知識(shí)點(diǎn)
1票编, 只要是函數(shù)就有 prototype
迄埃,__proto__
妄迁, 只要是對(duì)象就有 __proto__
屬性
對(duì)象無(wú) prototype 屬性
構(gòu)造函數(shù)有 proto prototype 屬性.png
2寝蹈, 通過(guò)構(gòu)造函數(shù)
可以創(chuàng)建實(shí)例對(duì)象
,實(shí)例對(duì)象
的 __proto__
指向 構(gòu)造函數(shù)
的 prototype
_proto_
作用是指向其構(gòu)造函數(shù)的prototype , 且構(gòu)造函數(shù)的prototype
是一個(gè)對(duì)象
注意是
構(gòu)造函數(shù)的prototype
登淘,而非構(gòu)造函數(shù)箫老,因此在創(chuàng)建構(gòu)造函數(shù)時(shí),如果要添加屬性方法只能添加到 構(gòu)造函數(shù)的prototype
上黔州,實(shí)例對(duì)象才能被繼承
3槽惫,函數(shù)的 prototype
屬性中有constructor
周叮,該屬性指向函數(shù)本身
通過(guò)創(chuàng)建實(shí)例對(duì)象解釋原型鏈
- var obj = {} 方法創(chuàng)建
var obj = {}
console.log(obj.__proto__ === Object.prototype)
console.log('Object.prototype', Object.prototype)
console.dir(Object.prototype.__proto__)
結(jié)果如下:
原型鏈為:
- 通過(guò)構(gòu)造函數(shù)創(chuàng)建對(duì)象和函數(shù)的原型鏈
- 1 對(duì)象
function Person (name, age) { this.name = name; this.age = age; } var person1 = new Person('張三', 14) console.log(person1)
如圖:
原型鏈為:
- 2 函數(shù)
var fn = new Function()
console.dir(fn)
打印結(jié)果:
原型鏈:
- 3 Object.create(Obj) 創(chuàng)建對(duì)象
實(shí)現(xiàn)原理:
Object.create = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
_相當(dāng)于創(chuàng)建一個(gè)實(shí)例對(duì)象, 對(duì)象的 __proto__
指向的是傳入的參數(shù)(即對(duì)象本身)界斜,而不是 對(duì)象的prototype
_
var ob = {}
var aaa = Object.create(ob)
console.log(aaa)
console.log(aaa.__proto__ === ob)
console.log(ob.__proto__ === Object.prototype)
原型鏈圖:
補(bǔ)充
var aa = function () {}
console.log(aa.prototype.__proto__ === aa.__proto__.__proto__) // true
// 可以把實(shí)例函數(shù) aa.prototype 看做 { constructor: aa仿耽,__proto__:Obeject.prototype對(duì)象 }