首页 > 解决方案 > 在实现我们自己的调用方法时,是否需要检查 typeof this == 'function' ?

问题描述

这是我自己的call方法的实现:

Function.prototype.myCall = function(thisArg,...args){
    if(typeof this != 'function'){
        throw new Error('myCall must be called via a function')
    }
    thisArg = thisArg ? Object(thisArg) : globalThis
    thisArg.fn = this
    const res = thisArg.fn(...args)
    delete thisArg.fn
    return res
}

但我不确定我是否应该typeof this != 'function'在这里检查。是的,调用者myCall必须是一个函数。但是即使我不检查这个,仍然会抛出一个错误。例如,执行时{a:1}.myCall(),会报错 {a:1}.myCall is not a function。并且由于我收到此错误,因此throw new Error('myCall must be called via a function')实际上无法执行。

标签: javascript

解决方案


检查是必要的typeof,因为一个对象可能是从Function.

如果我像这样删除检查:

Function.prototype.myCall = function(thisArg,...args){
    thisArg = thisArg ? Object(thisArg) : globalThis
    thisArg.fn = this
    const res = thisArg.fn(...args)
    delete thisArg.fn
    return res
}

还有一个像这样的对象:

const obj = Object.create(Function.prototype)
obj.myCall()

虽然obj实际上不是一个函数,但它可以调用myCall,因为它是从Function. 而且由于我没有检查this(在这种情况下obj)是否真的是一个函数,所以thisArg.fn调用会抛出一个错误。


推荐阅读