1. 程式人生 > >js 模擬call、apply、bind實現

js 模擬call、apply、bind實現

cal urn 需要 turn del typeof class 實現 function

1、模擬call實現

Function.prototype.myCall = function (context) {
  var context = context || window
  // 給 context 添加一個屬性
  // getValue.call(a, ‘yck‘, ‘24‘) => a.fn = getValue
  context.fn = this
  // 將 context 後面的參數取出來
  var args = [...arguments].slice(1)
  // getValue.call(a, ‘yck‘, ‘24‘) => a.fn(‘yck‘, ‘24‘)
var result = context.fn(...args) // 刪除 fn delete context.fn return result }

2、模擬apply實現

Function.prototype.myApply = function (context) {
  var context = context || window
  context.fn = this

  var result
  // 需要判斷是否存儲第二個參數
  // 如果存在,就將第二個參數展開
  if (arguments[1]) {
    result 
= context.fn(...arguments[1]) } else { result = context.fn() } delete context.fn return result }

3、模擬bind實現

Function.prototype.myBind = function (context) {
  if (typeof this !== ‘function‘) {
    throw new TypeError(‘Error‘)
  }
  var _this = this
  var args = [...arguments].slice(1)
  
// 返回一個函數 return function F() { // 因為返回了一個函數,我們可以 new F(),所以需要判斷 if (this instanceof F) { return new _this(...args, ...arguments) } return _this.apply(context, args.concat(...arguments)) } }

js 模擬call、apply、bind實現