天天看點

JavaScript 原型鍊、繼承

對象建立

javascript 中原型我們應該最熟悉,記得剛接觸js時候最長說的一句話就是,萬事萬物皆對象,額那時的我不怎麼懂,嗯。。。現在的我感覺說的js裡這麼說确實有一定的道理,可見js中對象的重要性。好的那麼建立對象的方法有以下幾種方式吧:

 以上那對象的建立方式:字面量、構造函數、Object.create();

原型鍊

記得當時項目開發中有個同僚問到我的一個問題,你給我講講原型鍊呗,上網搜了張圖,這張圖我覺得很能诠釋所有的關系清單,以及幾者之間有聯系,基本上很清晰:

// 構造函數 === >> 使用 new 運算符 生成的執行個體
// 構造函數生成 prototype ===>> 指向原型對象
// 原型對象怎麼能知道誰指向的自己 ===>> constructor 通過這個東西指向生成自己的構造函數。
// 執行個體中的__proto__ 指向的是 ===>> 原型對象
// 那麼原型鍊:就是這樣一層層找到最終的Object.prototype的原型對象就是一個鍊行結構。
// 舉個栗子:
const fn = function() {
    this.name="my name is GongXiaoZhu";
}
fn.prototype.say = function() {
    console.log(this.name);
}
var new_fn = new fn();
new_fn.__proto__ ===  fn.prototype // true
fn.prototype.constructor === fn // true
      

上述栗子足以說明原型、構造函數、執行個體、原型鍊之間的關系。是以對于幾個方法共同使用到的方法,我們完全可以定義到原型對象上,存儲到堆中,我們每個執行個體化的函數都可以拿到本方法。額,寫的最全的繼承方式圖:如下,這圖整懂應該原型鍊就木有啥東西。

繼承

1、借助構造函數實作繼承

function Parent1() {
    this.name = "zhangsan"
}
function Child1() {
    Parent1.call(this);// apply
    this.age = 'Child1'
}
var children1 = new Child1();
console.log(children1)
      

 此種繼承方式呐,由于改變的 Parent1 指向,不能繼承 Parent1 原型對象上的方法。隻能實作部分繼承。

2、組合繼承方式

function Parent1() {
    this.name = "zhangsan"
    this.arr = [1,2,3]
}
Parent1.prototype = function getName() {
    console.log(this.name);
}
function Child1() {
    Parent1.call(this);
    this.age = 'Child1'
}
Child1.prototype = new Parent1();

var a1 = new Child1();
var a2 = new Child1();
a1.arr.push('4')
console.log(a1,a2)
      

  

 從這裡我們可以實作繼承,但是還是有個弊端,Child1.prototype 對象指向的是Parent1.prototype,但是new Parent1() 的 constructor 指向的是 Parent1,是以我們可以直接Object.create(Parent1)這樣既可。

function Parent1() {
    this.name = "zhangsan"
    this.arr = [1,2,3]
}
Parent1.prototype = function getName() {
    console.log(this.name);
}

function Child1() {
    Parent1.call(this);
    this.age = 'Child1'
}
Child1.prototype = Object.create(Parent1.prototype);
Child1.prototype.constructor = Child1;

var a1 = new Child1();
var a2 = new Child1();
a1.arr.push('4')
console.log(a1,a2)
      

這樣就可以實作簡單的繼承,也希望能對您有所幫助,歡迎評論,關注,讨論技術可以關注 掘金 https://juejin.im/user/5cd2a2356fb9a0320c5ac8ad。