JS 原型及原型鏈學習

普通函數與構造函數的區別

  • 在命名規則上,構造函數通常是首字母大寫,普通函數遵守小駝峯式命名法。
  • 在函數調用的時候: function fn() { }
    構造函數:1. new fn( )數組

    2 .構造函數內部會建立一個新的對象,即f的實例
                     3. 函數內部的this指向 新建立的f的實例
                     4. 默認的返回值是f的實例
普通函數:1. fn( )
                  2. 在調用函數的內部不會建立新的對象
                  3. 函數內部的this指向調用函數的對象,此函數的調用者(若是沒有對象調用,默認是window)
                  4. 返回值由return語句決定
  • 構造函數的返回值:瀏覽器

    有一個默認的返回值,新建立的對象(實例);
       當手動添加返回值後(return語句):
            1. 返回值是基本數據類型-->真正的返回值仍是那個新建立的對象(實例)
            2. 返回值是複雜數據類型(對象)-->真正的返回值是這個對象

實例:app

function foo() {
    var f2 = new foo2();
    console.log(f2);  //{a: 3}
    console.log(this); //window
    return true;
  }
  function foo2() {
    console.log(this); //foo2類型的對象 不是foo2函數
//    this.age = 30;
    return {a: 3};
  }
  var f1 = foo();
  console.log(f1); // true

1、普通對象與函數對象

JavaScript 中,萬物皆對象!但對象也是有區別的。分爲普通對象和函數對象,Object 、Function 是 JS 自帶的函數對象。下面舉例說明函數

var o1 = {}; 
var o2 =new Object();
var o3 = new f1();

function f1(){}; 
var f2 = function(){};
var f3 = new Function('str','console.log(str)');

console.log(typeof Object); //function 
console.log(typeof Function); //function  

console.log(typeof f1); //function 
console.log(typeof f2); //function 
console.log(typeof f3); //function   

console.log(typeof o1); //object 
console.log(typeof o2); //object 
console.log(typeof o3); //object

在上面的例子中 o1 o2 o3 爲普通對象,f1 f2 f3 爲函數對象。怎麼區分,其實很簡單,凡是經過 new Function() 建立的對象都是函數對象,其餘的都是普通對象。f1,f2,歸根結底都是經過 new Function()的方式進行建立的。Function Object 也都是經過 New Function()建立的。
必定要分清楚普通對象和函數對象測試

2、構造函數

function Person(name, age, job) {
 this.name = name;
 this.age = age;
 this.job = job;
 this.sayName = function() { alert(this.name) } 
}
var person1 = new Person('Zaxlct', 28, 'Software Engineer');
var person2 = new Person('Mick', 23, 'Doctor');

上面的例子中 person1 和 person2 都是 Person 的實例。這兩個實例都有一個 constructor (構造函數)屬性,該屬性(是一個指針)指向 Person。 即:ui

console.log(person1.constructor == Person); //true
  console.log(person2.constructor == Person); //true

咱們要記住兩個概念(構造函數,實例):this

person1 和 person2 都是 構造函數 Person 的實例spa

實例的構造函數屬性(constructor)指向構造函數。

3、原型對象

在 JavaScript 中,每當定義一個對象(函數也是對象)時候,對象中都會包含一些預約義的屬性。其中每一個函數對象都有一個prototype 屬性,這個屬性指向函數的原型對象。(先用無論什麼是 __proto__ 第二節的課程會詳細的剖析)prototype

function Person() {}
Person.prototype.name = 'Zaxlct';
Person.prototype.age  = 28;
Person.prototype.job  = 'Software Engineer';
Person.prototype.sayName = function() {
  alert(this.name);
}
  
var person1 = new Person();
person1.sayName(); // 'Zaxlct'

var person2 = new Person();
person2.sayName(); // 'Zaxlct'

console.log(person1.sayName == person2.sayName); //true

每一個對象都有 __proto__ 屬性,但只有函數對象纔有 prototype 屬性

那什麼是原型對象呢?翻譯

咱們把上面的例子改一改你就會明白了:

Person.prototype = {
   name:  'Zaxlct',
   age: 28,
   job: 'Software Engineer',
   sayName: function() {
     alert(this.name);
   }
}

原型對象,顧名思義,它就是一個普通對象(廢話 = =!)。從如今開始你要緊緊記住原型對象就是 Person.prototype ,若是你仍是懼怕它,那就把它想一想成一個字母 A: var A = Person.prototype

在上面咱們給 A 添加了 四個屬性:name、age、job、sayName。其實它還有一個默認的屬性:constructor

在默認狀況下,全部的原型對象都會自動得到一個 constructor(構造函數)屬性,這個屬性(是一個指針)指向 prototype 屬性所在的函數(Person)

上面這句話有點拗口,咱們「翻譯」一下:A 有一個默認的 constructor 屬性,這個屬性是一個指針,指向 Person。即:

Person.prototype.constructor == Person

在上面第二小節《構造函數》裏,咱們知道實例的構造函數屬性(constructor)指向構造函數 :person1.constructor == Person
這兩個「公式」好像有點聯繫:

person1.constructor == Person
Person.prototype.constructor == Person

person1 爲何有 constructor 屬性?那是由於 person1 是 Person 的實例。
那 Person.prototype 爲何有 constructor 屬性??同理, Person.prototype (你把它想象成 A) 也是Person 的實例。
也就是在 Person 建立的時候,建立了一個它的實例對象並賦值給它的 prototype,基本過程以下:

var A = new Person();
 Person.prototype = A;

原型對象(Person.prototype)是 構造函數(Person)的一個實例。

四. --proto--

JS 在建立對象(不管是普通對象仍是函數對象)的時候,都有一個叫作__proto__ 的內置屬性,用於指向建立它的構造函數的原型對象。
對象 person1 有一個 __proto__屬性,建立它的構造函數是 Person,構造函數的原型對象是 Person.prototype ,因此:
person1.__proto__ == Person.prototype

clipboard.png

根據上面這個鏈接圖,咱們能獲得:

Person.prototype.constructor == Person;
person1.__proto__ == Person.prototype;
person1.constructor == Person;

不過,要明確的真正重要的一點就是,這個鏈接存在於實例(person1)與構造函數(Person)的原型對象(Person.prototype)之間,而不是存在於實例(person1)與構造函數(Person)之間。
注意:由於絕大部分瀏覽器都支持__proto__屬性,因此它才被加入了 ES6 裏(ES5 部分瀏覽器也支持,但還不是標準)。

五. 構造器

熟悉 Javascript 的童鞋都知道,咱們能夠這樣建立一個對象:

var obj = {}

它等同於下面這樣:

var obj = new Object()

obj 是構造函數(Object)的一個實例。因此:

obj.constructor === Object
obj.__proto__ === Object.prototype

新對象 obj 是使用 new 操做符後跟一個構造函數來建立的。構造函數(Object)自己就是一個函數(就是上面說的函數對象),它和上面的構造函數 Person 差很少。只不過該函數是出於建立新對象的目的而定義的。因此不要被 Object 嚇倒。

同理,能夠建立對象的構造器不只僅有 Object,也能夠是 Array,Date,Function等。
因此咱們也能夠構造函數來建立 Array、 Date、Function

var b = new Array();
b.constructor === Array;
b.__proto__ === Array.prototype;

var c = new Date(); 
c.constructor === Date;
c.__proto__ === Date.prototype;

var d = new Function();
d.constructor === Function;
d.__proto__ === Function.prototype;

clipboard.png

六. 原型鏈

小測試來檢驗一下你理解的怎麼樣:

person1.__proto__ 是什麼?

Person.__proto__ 是什麼?

Person.prototype.__proto__ 是什麼?

Object.__proto__ 是什麼?

Object.prototype__proto__ 是什麼?

答案:
第一題:
由於 person1.__proto__ === person1 的構造函數.prototype
由於 person1的構造函數 === Person
因此 person1.__proto__ === Person.prototype
第二題:
由於 Person.__proto__ === Person的構造函數.prototype
由於 Person的構造函數 === Function
因此 Person.__proto__ === Function.prototype
第三題:
Person.prototype 是一個普通對象,咱們無需關注它有哪些屬性,只要記住它是一個普通對象。
由於一個普通對象的構造函數 === Object
因此 Person.prototype.__proto__ === Object.prototype
第四題,參照第二題,由於 Person 和 Object 同樣都是構造函數
第五題:
Object.prototype 對象也有proto屬性,但它比較特殊,爲 null 。由於 null 處於原型鏈的頂端,這個只能記住。

Object.prototype.__proto__ === null

七. 函數對象 (複習一下前面的知識點)

全部函數對象的proto都指向Function.prototype,它是一個空函數(Empty function)

Number.__proto__ === Function.prototype  // true
Number.constructor == Function //true

Boolean.__proto__ === Function.prototype // true
Boolean.constructor == Function //true

String.__proto__ === Function.prototype  // true
String.constructor == Function //true

// 全部的構造器都來自於Function.prototype,甚至包括根構造器Object及Function自身
Object.__proto__ === Function.prototype  // true
Object.constructor == Function // true

// 全部的構造器都來自於Function.prototype,甚至包括根構造器Object及Function自身
Function.__proto__ === Function.prototype // true
Function.constructor == Function //true

Array.__proto__ === Function.prototype   // true
Array.constructor == Function //true

RegExp.__proto__ === Function.prototype  // true
RegExp.constructor == Function //true

Error.__proto__ === Function.prototype   // true
Error.constructor == Function //true

Date.__proto__ === Function.prototype    // true
Date.constructor == Function //true

JavaScript中有內置(build-in)構造器/對象共計12個(ES5中新加了JSON),這裏列舉了可訪問的8個構造器。剩下如Global不能直接訪問,Arguments僅在函數調用時由JS引擎建立,Math,JSON是以對象形式存在的,無需new。它們的proto是Object.prototype。以下

Math.__proto__ === Object.prototype  // true
Math.construrctor == Object // true

JSON.__proto__ === Object.prototype  // true
JSON.construrctor == Object //true

上面說的函數對象固然包括自定義的。以下

// 函數聲明
function Person() {}
// 函數表達式
var Perosn = function() {}
console.log(Person.__proto__ === Function.prototype) // true
console.log(Man.__proto__ === Function.prototype)    // true

這說明什麼呢?
全部的構造器都來自於 Function.prototype,甚至包括根構造器Object及Function自身。全部構造器都繼承了·Function.prototype·的屬性及方法。如length、call、apply、bind
(你應該明白第一句話,第二句話咱們下一節繼續說,先挖個坑:))
Function.prototype也是惟一一個typeof XXX.prototype爲 function的prototype。其它的構造器的prototype都是一個對象(緣由第三節裏已經解釋過了)。以下(又複習了一遍):

console.log(typeof Function.prototype) // function
console.log(typeof Object.prototype)   // object
console.log(typeof Number.prototype)   // object
console.log(typeof Boolean.prototype)  // object
console.log(typeof String.prototype)   // object
console.log(typeof Array.prototype)    // object
console.log(typeof RegExp.prototype)   // object
console.log(typeof Error.prototype)    // object
console.log(typeof Date.prototype)     // object
console.log(typeof Object.prototype)   // object

噢,上面還提到它是一個空的函數,console.log(Function.prototype) 下看看(留意,下一節會再說一下這個)
知道了全部構造器(含內置及自定義)的__proto__都是Function.prototype,那Function.prototype的__proto__是誰呢?
相信都據說過JavaScript中函數也是一等公民,那從哪能體現呢?以下

console.log(Function.prototype.__proto__ === Object.prototype) // true

這說明全部的構造器也都是一個普通 JS 對象,能夠給構造器添加/刪除屬性等。同時它也繼承了Object.prototype上的全部方法:toString、valueOf、hasOwnProperty等。(你也應該明白第一句話,第二句話咱們下一節繼續說,不用挖坑了,仍是剛纔那個坑;))
最後Object.prototype的proto是誰?

Object.prototype.__proto__ === null // true

已經到頂了,爲null。(讀到如今,再回過頭看第五章,能明白嗎?)

八. Prototype

在 ECMAScript 核心所定義的所有屬性中,最回味無窮的就要數 prototype 屬性了。對於 ECMAScript 中的引用類型而言,prototype 是保存着它們全部實例方法的真正所在。換句話所說,諸如 toString()valuseOf() 等方法實際上都保存在 prototype 名下,只不過是經過各自對象的實例訪問罷了。

——《JavaScript 高級程序設計》第三版 P116
咱們知道 JS 內置了一些方法供咱們使用,好比:
對象能夠用 constructor/toString()/valueOf() 等方法;
數組能夠用 map()/filter()/reducer() 等方法;
數字可用用 parseInt()/parseFloat()等方法;

當咱們建立一個函數時:

var Person = new Object()

PersonObject 的實例,因此 Person 繼承了Object 的原型對象Object.prototype上全部的方法:

clipboard.png

Object 的每一個實例都具備以上的屬性和方法。
因此我能夠用 Person.constructor 也能夠用 Person.hasOwnProperty。

當咱們建立一個數組時:

var num = new Array()

numArray 的實例,因此 num 繼承了Array 的原型對象Array.prototype上全部的方法:

clipboard.png

怎麼是一個空數組???

咱們能夠用一個 ES5 提供的新方法:Object.getOwnPropertyNames
獲取全部(包括不可枚舉的屬性)的屬性名不包括 prototy 中的屬性,返回一個數組:

var arrayAllKeys = Array.prototype; // [] 空數組
// 只獲得 arrayAllKeys 這個對象裏全部的屬性名(不會去找 arrayAllKeys.prototype 中的屬性)
console.log(Object.getOwnPropertyNames(arrayAllKeys)); 
/* 輸出:
["length", "constructor", "toString", "toLocaleString", "join", "pop", "push", 
"concat", "reverse", "shift", "unshift", "slice", "splice", "sort", "filter", "forEach", 
"some", "every", "map", "indexOf", "lastIndexOf", "reduce", "reduceRight", 
"entries", "keys", "copyWithin", "find", "findIndex", "fill"]
*/

這樣你就明白了隨便聲明一個數組,它爲啥能用那麼多方法了。
細心的你確定發現了Object.getOwnPropertyNames(arrayAllKeys) 輸出的數組裏並無 constructor/hasOwnPrototype等對象的方法(你確定沒發現)。
可是隨便定義的數組也能用這些方法

var num = [1];
console.log(num.hasOwnPrototype()) // false (輸出布爾值而不是報錯)

Why ???

由於Array.prototype 雖然沒這些方法,可是它有原型對象(__proto__):

// 上面咱們說了 Object.prototype 就是一個普通對象。
Array.prototype.__proto__ == Object.prototype

因此 Array.prototype 繼承了對象的全部方法,當你用num.hasOwnPrototype()時,JS 會先查一下它的構造函數 (Array) 的原型對象 Array.prototype 有沒有有hasOwnPrototype()方法,沒查到的話繼續查一下 Array.prototype 的原型對象 Array.prototype.__proto__有沒有這個方法。

當咱們建立一個函數時:

var f = new Function("x","return x*x;");
//固然你也能夠這麼建立 f = function(x){ return x*x }
console.log(f.arguments) // arguments 方法從哪裏來的?
console.log(f.call(window)) // call 方法從哪裏來的?
console.log(Function.prototype) // function() {} (一個空的函數)
console.log(Object.getOwnPropertyNames(Function.prototype)); 
/* 輸出
["length", "name", "arguments", "caller", "constructor", "bind", "toString", "call", "apply"]
*/

咱們再複習第八小節這句話:

全部函數對象proto都指向 Function.prototype,它是一個空函數(Empty function)

嗯,咱們驗證了它就是空函數。不過不要忽略前半句。咱們枚舉出了它的全部的方法,因此全部的函數對象都能用,好比:

clipboard.png

若是你還沒搞懂啥是函數對象?

還有,我建議你能夠再複習下爲何:

Function.prototype 是惟一一個typeof XXX.prototype爲 「function」的prototype

我猜你確定忘了。

九. 複習一下

第八小節咱們總結了:

全部函數對象的 __proto__ 都指向 Function.prototype,它是一個空函數(Empty function)

可是你可別忘了在第三小節咱們總結的:

全部對象的 __proto__ 都指向其構造器的 prototype

咦,我找了半天怎麼沒找到這句話……

咱們下面再複習下這句話。

先看看 JS 內置構造器:

var obj = {name: 'jack'}
var arr = [1,2,3]
var reg = /hello/g
var date = new Date
var err = new Error('exception')
 
console.log(obj.__proto__ === Object.prototype) // true
console.log(arr.__proto__ === Array.prototype)  // true
console.log(reg.__proto__ === RegExp.prototype) // true
console.log(date.__proto__ === Date.prototype)  // true
console.log(err.__proto__ === Error.prototype)  // true

再看看自定義的構造器,這裏定義了一個 Person:

function Person(name) {
  this.name = name;
}
var p = new Person('jack')
console.log(p.__proto__ === Person.prototype) // true

pPerson 的實例對象,p 的內部原型老是指向其構造器 Person 的原型對象 prototype

每一個對象都有一個 constructor 屬性,能夠獲取它的構造器,所以如下打印結果也是恆等的:

function Person(name) {
    this.name = name
}
var p = new Person('jack')
console.log(p.__proto__ === p.constructor.prototype) // true

上面的Person沒有給其原型添加屬性或方法,這裏給其原型添加一個getName方法:

function Person(name) {
    this.name = name
}
// 修改原型
Person.prototype.getName = function() {}
var p = new Person('jack')
console.log(p.__proto__ === Person.prototype) // true
console.log(p.__proto__ === p.constructor.prototype) // true

能夠看到p.__proto__Person.prototype,p.constructor.prototype都是恆等的,即都指向同一個對象。
若是換一種方式設置原型,結果就有些不一樣了:

function Person(name) {
    this.name = name
}
// 重寫原型
Person.prototype = {
    getName: function() {}
}
var p = new Person('jack')
console.log(p.__proto__ === Person.prototype) // true
console.log(p.__proto__ === p.constructor.prototype) // false

這裏直接重寫了 Person.prototype(注意:上一個示例是修改原型)。輸出結果能夠看出p.__proto__仍然指向的是Person.prototype,而不是p.constructor.prototype

這也很好理解,給Person.prototype賦值的是一個對象直接量{getName: function(){}},使用對象直接量方式定義的對象其構造器(constructor)指向的是根構造器ObjectObject.prototype是一個空對象{},{}天然與{getName: function(){}}不等。以下:

var p = {}
console.log(Object.prototype) // 爲一個空的對象{}
console.log(p.constructor === Object) // 對象直接量方式定義的對象其constructor爲Object
console.log(p.constructor.prototype === Object.prototype) // 爲true,不解釋(๑ˇ3ˇ๑)

十. 原型鏈(再複習一下:)

下面這個例子你應該能明白了!

function Person(){}
var person1 = new Person();
console.log(person1.__proto__ === Person.prototype); // true
console.log(Person.prototype.__proto__ === Object.prototype) //true
console.log(Object.prototype.__proto__) //null

Person.__proto__ == Function.prototype; //true
console.log(Function.prototype)// function(){} (空函數)

var num = new Array()
console.log(num.__proto__ == Array.prototype) // true
console.log( Array.prototype.__proto__ == Object.prototype) // true
console.log(Array.prototype) // [] (空數組)
console.log(Object.prototype.__proto__) //null

console.log(Array.__proto__ == Function.prototype)// true

疑點解惑:

1. Object.__proto__ === Function.prototype // true
      Object 是函數對象,是經過new Function()建立的,因此Object.__proto__指向Function.prototype。(參照第八小節:「全部函數對象的__proto__都指向Function.prototype」)



 2. Function.__proto__ === Function.prototype // true
    Function 也是對象函數,也是經過new Function()建立,因此Function.__proto__指向Function.prototype。

本身是由本身建立的,好像不符合邏輯,但仔細想一想,現實世界也有些相似,你是怎麼來的,你媽生的,你媽怎麼來的,你姥姥生的,……類人猿進化來的,那類人猿從哪來,一直追溯下去……,就是無,(NULL生萬物)
正如《道德經》裏所說「無,名天地之始」。

3.Function.prototype.__proto__ === Object.prototype //true

其實這一點我也有點困惑,不過也能夠試着解釋一下。
Function.prototype是個函數對象,理論上他的__proto__應該指向 Function.prototype,就是他本身,本身指向本身,沒有意義。
JS一直強調萬物皆對象,函數對象也是對象,給他認個祖宗,指向Object.prototypeObject.prototype.__proto__ === null,保證原型鏈可以正常結束。

十一 總結

原型和原型鏈是JS實現繼承的一種模型。
原型鏈的造成是真正是靠__proto__ 而非prototype

要深刻理解這句話,咱們再舉個例子,看看前面你真的理解了嗎?

var animal = function(){};
 var dog = function(){};

 animal.price = 2000;
 dog.prototype = animal;
 var tidy = new dog();
 console.log(dog.price) //undefined
 console.log(tidy.price) // 2000

這裏解釋一下:

var dog = function(){};
 dog.prototype.price = 2000;
 var tidy = new dog();
 console.log(tidy.price); // 2000
 console.log(dog.price); //undefined

 var dog = function(){};
 var tidy = new dog();
 tidy.price = 2000;
 console.log(dog.price); //undefined

這個明白吧?想想咱們上面說過這句話:

實例(tidy)和 原型對象(dog.prototype)存在一個鏈接。不過,要明確的真正重要的一點就是,這個鏈接存在於實例(tidy)與構造函數的原型對象(dog.prototype)之間,而不是存在於實例(tidy)與構造函數(dog)之間。

本文轉載自 簡書 Yi罐可樂
https://www.jianshu.com/p/dee...
https://www.jianshu.com/p/652...
https://www.jianshu.com/p/a4e...

相關文章
相關標籤/搜索