前端面試必問的一題~javascript原型和繼承

這篇文章是從以下幾個方面著手

  • 0怎么理解面向?qū)ο?/li>
  • 1創(chuàng)建對象的方式
  • 2記住原型鏈的小竅門
  • 3instanceof 模擬實現(xiàn)
  • 4new關(guān)鍵字 模擬實現(xiàn)
  • 5繼承的實現(xiàn)(逐步實現(xiàn))

0 怎么理解面向?qū)ο?/h2>

其實我也不知道咋回答這問題,我只知道,面試官問這個后,就表示他要問一堆繼承的問題了。下面是引用周老師的一段說辭。

"面向?qū)ο笫且环N編程思想 與面向過程是對應(yīng)的 一般的語言都是面向?qū)ο蟮?js本身也是基于面向?qū)ο髽?gòu)建出來的 ,例如 js本身就有很多內(nèi)置類,Promise就是,可以new Promise來創(chuàng)建一個實例,來管理異步編程 。 還有vue 也是,平時都是創(chuàng)建vue的實例啊。"

1 創(chuàng)建對象的方式

1.對象字面量

var o1 = {name: 'o1'}
var o2 = new Object({name: 'o2'})

2.通過構(gòu)造函數(shù)

var M = function(name){
    this.name = name
}
var o3 = new M('o3')

3.Object.create

var o4 = Object.create(p)

2 記住原型鏈的小竅門

記憶總是有規(guī)律的,如高中時期學的三角函數(shù),需要背公式很多,強行去背全部的公式是容易混亂的。不過如果把核心的幾點背牢,其余的公式只需要稍加推導即可。關(guān)于原型鏈也是一樣,有幾點在最開始就記住的話,后面就不會亂了。原型鏈中關(guān)鍵概念: 構(gòu)造函數(shù) , 實例 , constructor ,*proto , prototype , 首先要記住他們的關(guān)系。

  • 實例(對象)有__ proto __ , 實例(對象)沒有prototype
  • 構(gòu)造函數(shù)有 prototype ,同時prototype又是對象,那么prototype即滿足上面一條,除了擁有proto外,還含有constructor
  • 構(gòu)造函數(shù)的prototype的constructor就是指向構(gòu)造函數(shù)本身,即上例子中 M.prototype.constructor === M
    上面3點請先牢記,后面所總結(jié)的完整繼承和這有緊密的關(guān)聯(lián)

其實 構(gòu)造函數(shù) , 實例constructor , proto , prototype的關(guān)系已經(jīng)在上面的例子和3點介紹中介紹完了。不妨再回顧一下

1.構(gòu)造函數(shù)即普通函數(shù),只不過前邊有 new 關(guān)鍵字
2.通過 new構(gòu)造函數(shù) ,生成的對象即為實例。
3.以上面生成o3實例為例子

o3.__proto__ === M.prototype  //true

 o3.prototype   //undefined

 o3.__proto__ === M.prototype //true

4.o3實例本身并無constructor,不過會借助原型鏈向上查找,即

o3.constructor === M.prototype.constructor  // true

 o3.constructor === M //true

小結(jié) 理清這幾個關(guān)鍵詞的關(guān)系后,原型鏈就明朗很多了

3 instanceof 模擬實現(xiàn)

instanceof 的原理是什么呢? 先來看一下使用

[] instanceof Array  // true

即左邊是對象,右邊是類型,instanceof 就是要判斷右邊類型的prototype,是否在左邊實例的原型鏈上,如下例子所示

[].__proto__ === Array.prototype //true
Array.prototype.__proto__ === Object.prototype //true
Object.prototype__proto__ //null

那么依據(jù)這個思想來實現(xiàn)一下instanceof吧,一定會印象更加深刻

function myInstanceof2(left, right){
    if(left === null || left === undefined){
        return false
    }
    if(right.prototype === left.__proto__) {
        return true
    }

    left = left.__proto__
    return myInstanceof2(left, right)
}

console.log(myInstanceof2([], Array))

4 new 模擬實現(xiàn)(簡要版)

new的過程發(fā)生了什么?

1.生成空對象
2.這個空對象的proto賦值為構(gòu)造函數(shù)的prototype
3.綁定this指向
4.返回這個對象

// 構(gòu)造函數(shù)
 function M(name){
     this.name = name
 }
 // 原生new
 var obj = new M('123')

 // 模擬實現(xiàn)
 function create() {
   // 生成空對象
   let obj = {}
   // 拿到傳進來參數(shù)的第一項,并改變參數(shù)類數(shù)組
   let Con = [].shift.call(arguments)
   // 對空對象的原型指向賦值
   obj.__proto__ = Con.prototype
   // 綁定this 
   //(對應(yīng)下面使用來說明:Con是參數(shù)第一項M,
   // arguments是參數(shù)['123'],
   // 就是 M方法執(zhí)行,參數(shù)是'123',執(zhí)行這個函數(shù)的this是obj)
   let result = Con.apply(obj, arguments)
   return result instanceof Object ? result : obj
 }

 var testObj = create(M, '123')
 console.log('testObj', testObj)

5 繼承的實現(xiàn)(逐步實現(xiàn))

一步一步來,從簡到繁,更能直觀發(fā)現(xiàn)繼承的原理與缺點

1.構(gòu)造方法方式 核心 Parent1.call(this)

// 構(gòu)造方法方式
 function Parent1(){
     this.name = 'Parent1'
 }
 Parent1.prototype.say = function () {
     alert('say')
 }
 function Child1(){
     Parent1.call(this)
     this.type = 'type'
 }

 var c1 = new Child1()
 c1.say() //報錯

思考: 為什么 call 實現(xiàn)了繼承,call本質(zhì)是什么?

1.只借助原型繼承 核心 Child2.prototype = new Parent2()

// 原型
 function Parent2(){
     this.name = 'Parent2'
     this.arr = [1,2]
 }
 Parent2.prototype.say = function () {
     alert('say')
 }
 function Child2(){
     // Parent2.call(this)
     this.type = 'type'
 }
 Child2.prototype = new Parent2()

 var c21 = new Child2()
 var c22 = new Child2()

 c21.say()
 c21.arr.push('9')
 console.log('c21.arr : ', c21.arr)
 console.log('c22.arr : ', c22.arr)

思考:為什么這么寫是同一個引用?

1.組合繼承1
把上面兩個繼承方式的優(yōu)點合并起來,缺點都拋棄掉

    this.name = 'Parent3'
    this.arr = [1,2]
}
Parent3.prototype.say = function () {
    alert('say')
}
function Child3(){
    Parent3.call(this)
    this.type = 'type'
}
Child3.prototype = new Parent3()

var c31 = new Child3()
var c32 = new Child3()

c31.say()
c31.arr.push('9')
console.log('c31.arr : ', c31.arr)
console.log('c31.arr : ', c32.arr)

答 : 生成一個實例要執(zhí)行 Parent3.call(this) , new Child3(),也就是Parent3執(zhí)行了兩遍。

1.組合繼承2
改變上例子的

Child3.prototype = new Parent3()

Child3.prototype = Parent3.prototype

缺點 : 很明顯,無法定義子類構(gòu)造函數(shù)原型私有的方法

1.組合繼承優(yōu)化3 再次改變上例子的

Child3.prototype = Parent3.prototype

Child3.prototype = Object.create(Parent3.prototype)

思考 :是否還有疏漏?一時想不起來的話,可以看下這幾個結(jié)果

console.log(c31 instanceof Child3) // true
console.log(c31 instanceof Parent3) // true
console.log(c31.constructor === Child3) // false
console.log(c31.constructor === Parent3) // true

所以回想起文章開頭所說的那幾個需要牢記的點,就需要重新賦值一下子類構(gòu)造函數(shù)的constructor: Child3.prototype.constructor = Child3,完整版如下

function Parent3(){
    this.name = 'Parent3'
    this.arr = [1,2]
}
Parent3.prototype.say = function () {
    alert('say')
}
function Child3(){
    Parent3.call(this)
    this.type = 'type'
}

Child3.prototype = Object.create(Parent3.prototype)
Child3.prototype.constructor = Child3

var c31 = new Child3()
var c32 = new Child3()

c31.say()
c31.arr.push('9')
console.log('c31.arr : ', c31.arr)
console.log('c31.arr : ', c32.arr)

console.log('c31 instanceof Child3 : ', c31 instanceof Child3)
console.log('c31 instanceof Parent3 : ', c31 instanceof Parent3)
console.log('c31.constructor === Child3 : ', c31.constructor === Child3)
console.log('c31.constructor === Parent3 : ', c31.constructor === Parent3)

5 es6的繼承

class Parent{
  constructor(name) {
    this.name = name
  }
  getName(){
    return this.name
  }
}

class Child{
  constructor(age) {
    this.age = age
  }
  getAge(){
    return this.age
  }
}

es6繼承記住幾個注意事項吧

  • 1 構(gòu)造函數(shù)不能當普通函數(shù)一樣執(zhí)行 Parent() 是會報錯的
  • 2 不允許重定向原型 Child.prototype = Object.create(Parent.prototype) 無用
  • 3 繼承寫法如下,上面的Child類想繼承父類,改成如下寫法就好


<figcaption></figcaption>

注意寫了extends關(guān)鍵字,constructor中就必須寫super(),打印結(jié)果如下:

最后

平時一直有整理面試題的習慣,有隨時跳出舒適圈的準備,也歡迎大家加裙獲取~

我的資料嗎?想要的話可以全部給你,我將所有的資源都放在了那!


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容