js常見原理面試題

1. 實現一個call函數

// 將要改變this指向的方法掛到目標this上執行并返回

Function.prototype.call = function(context) {
    if( typeof this !== 'function') {
        throw new TypeError('not function')
    }
    context = context || window
    context.fn = this
    let arg = [...arguments].slice(1)
    let result = context.fn(...arg)
    delete context.fn
    return result 
}

2. 實現一個apply函數

Function.prototype.apply = function(contex) {
    if( typeof this !== 'function') {
        throw new TypeError('not function')
    }
    context = context || window
    context.fn = this
    let result 
    if(argument[1]) {
        result = context.fn(...argument[1])
    } else {
        result = context.fn()
    }
    delete context.fn
    return result
}

3. 實現一個bind函數

Function.prototype.bind = function(context) {
    if( typeof this !== 'function') {
        throw new TypeError('not function')
    }
    let _this = this
    let arg = [...arguments].slice(1)
    // 處理使用 new 的情況
    return function F(){
        if(this instanceof F) {
            return new _this(...arg, ...arguments)
        } else {
            return _this.apply(context, arg.concat(...arguments))
        }
    }
}

4. instanceof原理

A instanceof B 用于判斷 A 的原型鏈中是否有 B 的存在,相當于右邊 B 的變量原型是否在左邊 A 的原型鏈上

// 右邊變量的原型存在于左邊變量的原型鏈上
function instanceof(left, right) {
    let leftValue = left.__proto__
    let rightValue = right.prototype
    // 循環查找,找到返回
    while (true) {
        if(leftValue === null) {
            return false
        }
        if(leftValue === rightValue) {
            return true
        }
        leftValue = leftValue.__proto__
    }
}

5. Object.create 原理

create 創建一個空對象,將傳入的參數作為創建后對象的原型

function create(obj) {
    function F(){}
    F.prototype = obj
    return new F()
}

6. new 本質

new 是可以進行調用構造函數的 constructor

function
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Swift1> Swift和OC的區別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴謹 對...
    cosWriter閱讀 11,145評論 1 32
  • 一、 JS面向對象編程 1、 面向對象介紹 什么是對象? Everything is object (萬物皆對象)...
    寵辱不驚丶歲月靜好閱讀 849評論 0 2
  • 概要 64學時 3.5學分 章節安排 電子商務網站概況 HTML5+CSS3 JavaScript Node 電子...
    阿啊阿吖丁閱讀 9,341評論 0 3
  • ??面向對象(Object-Oriented,OO)的語言有一個標志,那就是它們都有類的概念,而通過類可以創建任意...
    霜天曉閱讀 2,140評論 0 6
  • (原創首發,不得轉載) 夏至翩翩來,夫妻約草忙。 遙望菩提樹,幸福綿又長。
    財道閱讀 633評論 0 12