實現call, apply, bind函式

2021-09-25 18:34:49 字數 1568 閱讀 6071

思路:把目標儲存在this中並返回

const obj = 

let name = '李四'

function add()

// 執行函式

add() // 李四

add.call(obj) // 張三

1.實現call函式定義名稱為mycall

function.prototype.mycall = function(content) 

content = content || window // content存在就用content,否則window

content.fn = this

let arg = [...arguments].slice(1) // 反回引數

let result = content.fn(...arg)

delete content.fn

return result

}const obj =

let name = '李四'

function add()

add.mycall(obj) // 張三

function add(x, y)

add.mycall(obj, 1, 2) // 張三

const obj = 

let name = '李四'

function add()

// 執行函式

add() // 李四

function add(x, y)

// 執行函式

道理都是一樣

if (typeof this !== 'function')

content = content || window // content存在就用content,否則window

content.fn = this

let result

if (arguments[1]) else

delete content.fn

return result

}const obj =

let name = '李四'

function add()

function add(x, y)

接下來就是bind函式,它返回的是乙個函式

function.prototype.mybind = function(content) 

let that = this

let arg = [...arguments].slice(1)

return function b() else

// arg 是第乙個括號後面的引數

// ...arguments 是第二個括號後面的引數

}}const obj =

var name = '李四'

function da(x, y)

da.mybind(obj, 1, 2)()

function da(x, y, z, d)

da.mybind(obj, 1, 2)(3, 4)

手動實現call apply bind

第一種方式 function.prototype.mycall function context,args 第二種方式 function.prototype.mycall2 function context 測試 let person call 我今年 我的工作是 let person1 perso...

call apply bind 實現原理

眾所周知這三個方法都是提供給 函式使用的,函式通過這三個方法呼叫把 this 傳入進去就可以改變其 this 指向。通過這個特性我們可以推斷出 這三個方法都是寫在function物件的原型上的。也就是function.prototype上 下邊我們先在這個原型上寫乙個自己的 call 方法就叫new...

js手動實現call,apply,bind

原文 我也不知道為什麼只能顯示一部分 好氣哦 看原文吧 先分析下3個方法的作用 改變this的指向 首先我們知道,物件上的方法,在呼叫時,this是指向物件的。let o o.fn object 函式原型上新增 mycall方法 來模擬call function.prototype.mycall f...