javascript - 在实现我们自己的调用方法时,是否需要检查 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')
实际上无法执行。
解决方案
检查是必要的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
调用会抛出一个错误。
推荐阅读
- outlook - 如果在 OWA 上使用稍后发送选项,Office.context.mailbox.item.SaveAsync 会在 Onsend 插件中引发错误
- java - 如何将值从活动传递到广播接收器?putExtra 对我不起作用
- python - db.session.commit() 在实例方法 flask sqlalchemy 中不起作用
- html - 日期管道格式问题
- ethereum - 以太坊如何进行 DAO 攻击?
- flutter - 从 listView 保存计数器值
- html - 尝试使用 Css 创建选项卡时出错?
- spring-boot - 在 SpringBoot 中,@JmsListener 如何以及何时被调用?
- javascript - 当我单击一个 div 然后它隐藏其他 div 时我想做
- rest - 我可以使用分块编码使用 Java REST API 下载巨大的静态文件吗?