bind,apply,call的區別和實現

2021-10-05 08:07:16 字數 1230 閱讀 5371

fn.bind(null, 1, 2, 3)

fn.call(null, 1, 2, 3)

1.call

function.prototype.macall = function (context, ...args) 

context = context || window;

context.$fn = this;

const result = context.$fn(...args);

delete context.$fn;

return result;

}

if (typeof this !== 'function')

context = context || window;

context.fn = this;

let result;

if (args.length) else

delete context.fn;

return result;};

3.bind

function.prototype.mybind = function (context) 

const that = this;

const args = [...arguments].slice(1);

return function f() else

};};

順便實現乙個new:

不過在實現之前先看看new的過程中都做了什麼

1.新建乙個物件

2.鏈結到原型

3.繫結this

4.返回這個物件

function mynew() ;

// 獲取建構函式

const con = .shift.call(arguments);

// 設定空物件的原型

obj.__proto__ = con.prototype;

// 繫結this,執行建構函式

// 確保返回值為物件

return result instanceof object ? result : obj;

}

還有一種更簡單的實現方式,通過object.create,直接指定原型鏈

function _new(fn, ...args)

bind apply call之間的差異

假定存在如下的上下文與函式 待測試的上下文 var context 待測試的函式 function output name,hello 上下文繫結後的引數必須是陣列 上下文後的就是引數列表 alert output.call context,call hi 輸出hi,call 函式繫結bind後並沒...

也談如何實現bind apply call

本文先給出如下類定義和例項定義。person類,每個人有姓名,有列印姓名的方法 function person name 兩個例項 let alex new person alex let bob new person bob 不妨先回顧一下bind的使用方法 let saybobname alex...

記憶體的使用 棧區 堆區 靜態區 唯讀區

記憶體的使用感覺好亂啊,需要整理一下!於是參考c primer與網上資源,整理如下 一 綜述 記憶體中的棧區分配的是區域性變數和函式的引數值的空間,棧的生長方向是從高往低的 堆區是向上增長的用於分配程式設計師申請的記憶體空間 比如new 申請的動態記憶體 注意它與資料結構中的堆是兩回事,分配方式倒是...