面向對象精要-構造函數和原型對象
阿新 • • 發佈:2018-04-19
需要 type屬性 image 原型對象 實例對象 col class .get 指向
1、構造函數
function Person() { }
構造函數-----首字母大寫
1.1、實例化對象
function Person() { } var person1 = new Person()
1.2、檢測對象類型
instanceof 方法
function Person() { } var person1 = new Person(); console.log(person1 instanceof Person);/*true*/
constructor 方法
function Person() { }var person1 = new Person(); console.log(person1.constructor === Person);/*true*/
建議使用instanceof檢測對象類型,因為構造函數屬性可以被覆蓋,並不一定完全準確。
2、原型對象
原型對象好比對象的基類。
幾乎所有的函數都有一個名為prototype的屬性,該屬性數一個原型對象用來創建新的對象實例。
2.1、[[Prototype]]屬性
實例對象的內部屬性,跟蹤到原型對象。
指向該實例使用的原型對象的一個指針。
讀取方法:
Object.getPrototypeOf()
functionPerson() { } var person1 = new Person(); var prototype = Object.getPrototypeOf(person1); console.log(prototype === Person.prototype)/*true*/
大部分引擎在所有對象上都支持一個名為__proto__的屬性。該屬性可以直接讀寫[[Prototype]]屬性。
2.2、在構造函數中使用原型對象
function Person(name) { this.name = name; } Person.prototype.sayName= function () { console.log(this.name) }; var person1 = new Person("Qian"); var person2 = new Person("Wei"); person1.sayName(); //Qian person2.sayName(); //Wei
sayName()現在是一個原型屬性而不是自有屬性
添加多個屬性,簡潔的方法
function Person(name) { this.name = name; } Person.prototype = { sayName:function () { console.log(this.name) }, toString:function () { return "[Person "+this.name+"]" } }; var person1 = new Person("Qian"); person1.sayName();/*Qian*/ console.log(person1.toString());/*[Person Qian]*/
副作用
function Person(name) { this.name = name; } Person.prototype = { sayName:function () { console.log(this.name) }, toString:function () { return "[Person "+this.name+"]" } }; var person1 = new Person("Qian"); person1.sayName();/*Qian*/ console.log(person1.toString());/*[Person Qian]*/ console.log(person1 instanceof Person);/*true*/ console.log(person1.constructor === Person);/*false*/ console.log(person1.constructor === Object);/*true*/
使用對象字面量形式改寫原型對象改變了構造函數的屬性,因此他現在指向Object而不是Person。
原因:原型對象具有一個constructor屬性,這是其他對象實例所沒有的,當一個函數被創建時,它的prototype屬性也被創建,且該原型對象的constructor屬性指向該函數。當使用對象字面形式改寫原型對象的Person.prototype時,其constructor屬性將被置為泛用對象Object()。
解決辦法:需要在改寫原型對象時手動重置為constructor屬性
function Person(name) { this.name = name; } Person.prototype = { constructor:Person, sayName:function () { console.log(this.name) }, toString:function () { return "[Person "+this.name+"]" } }; var person1 = new Person("Qian"); person1.sayName();/*Qian*/ console.log(person1.toString());/*[Person Qian]*/ console.log(person1 instanceof Person);/*true*/ console.log(person1.constructor === Person);/*true*/ console.log(person1.constructor === Object);/*false*/
2.3、內建對象的原型對象
Array.prototype.sum = function () { return this.reduce(function (pre,cur) { return pre+cur; }); }; var number = [1,2,3,4,5]; console.log(number.sum())/*15*/
在Array.prototype上創建一個名為sum()方法。
面向對象精要-構造函數和原型對象