這幾天閒了看了下js的原型,如下內容爲我的理解,若有錯誤,盡請指正。函數
首先,明確一點:js中的對象分爲普通對象和函數對象,通常咱們自定義的能夠被new的函數稱做函數對象,另外js內置了譬如:Array、Date、Object、Function、Number、String、Boolean、RegExp、Error等這些函數對象:this
一、只有函數對象纔有prototype屬性,該屬性指向的俗稱「原型」或者「原型對象」,舉個栗子:prototype
function Person() {} console.log(Person.prototype) // {constructor: Person, __proto__: Object}
二、每一個原型或者原型對象還有一個constructor屬性,即上面的Person.prototype.constructor,該屬性指向該函數的構造,這裏指向Person自身,即:code
Person.prototype.constructor === Person // true
三、全部對象,不論普通對象仍是函數對象都有一個__proto__屬性,該屬性指向其構造的原型,使用__proto__將全部對象聯繫起來,才造成了所謂的原型鏈,舉個栗子:對象
function Person() {} const p1 = new Person() console.log(p1.__proto__ === Person.prototype) // true, p1是由Person構造的 console.log(Person.prototype.__proto__ === Object.prototype) // true, Person的原型是由Object構造的,由於Person.prototype是一個普通對象,普通對象的構造都是Object console.log(Person.__proto__ === Function.prototype) // true, Person是由Function構造的 console.log(Function.__proto__ === Function.prototype) // true, Function是由自身構造的 console.log(Function.prototype.__proto__ === Object.prototype) // true, Function的原型是由Object構造的 console.log(Object.__proto__ === Function.prototype) // true, Object是由Function構造的,相似Person.__proto__ console.log(Date.__proto__ === Function.prototype) // true, Date是由Function構造的,相似Person.__proto__ console.log(String.__proto__ === Function.prototype) // true, String是由Function構造的,相似Person.__proto__ console.log(Boolean.__proto__ === Function.prototype) // true,Boolean是由Function構造的,相似Person.__proto__ console.log(Object.prototype.__proto__ === null) // true, Object的原型是由null"產生"的,null處於原型鏈頂端
這個從根本上印證了道德經那句:道(null)生一,一輩子二,二生三,三生萬物。無,名天地之始。blog
四、通常咱們經過.操做符獲取一個對象的屬性或方法的時候,會首先在當前對象自身上查找該屬性或方法,找不到的話會繼續順着__proto__也就是原型鏈向上查找,直到找到,不然返回undefined,舉個栗子:繼承
function Person() { this.name = 'Nicholas' this.age = 29 this.job = 'Software Engineer' this.sayName = function() { console.log(this.name) } } const person1 = new Person() const person2 = new Person() person1.sayName() person2.sayName()
[[Prototype]]即上面所說的__proto__,由上圖能夠直接得出以下結論:圖片
Person.prototype.constructor == Person; person1.__proto__ == Person.prototype; person1.constructor == Person;
當咱們獲取person1.age時,發現person1自身並沒有age屬性,因此會自動向上查找person1.__proto__.age,發現有併爲29,則直接返回29,即person1.age === 29原型鏈
function Person() { this.name = 'Nicholas' this.age = 29 this.job = 'Software Engineer' this.sayName = function() { console.log(this.name) } } const person1 = new Person() console.log(person1.age === 29) // true
同理,查找person1.constructor時會自動查找到Person自身,因此以下是恆等的:原型
function Person(name) { this.name = name } var p = new Person('jack') console.log(p.__proto__ === p.constructor.prototype) // true
下一節的話講下js中的繼承~