检查是否定义了对象/函数(JavaScript、Safari问题)

Check whether an object/function is defined (JavaScript, Safari issue)

本文关键字:JavaScript Safari 问题 函数 定义 是否 对象 检查      更新时间:2023-09-26

我想检查是否可以使用对象/函数,例如window.performance.now()if(typeof window.performance.now != 'undefined')运行良好,但Safari(5.1.7,Windows)除外,它返回TypeError: 'undefined' is not an object (evaluating 'window.performance.now')。为了避免混淆:console.log(typeof window.performance.now)返回相同的错误。

因为Safari不支持window.performance对象本身。所以你检查会更安全

typeof window.performance !== 'undefined' && typeof window.performance.now !== 'undefined'

更新

第一个检查是查看window.performance对象是否存在。第二个检查是查看.now()函数在window.performance对象中是否可用。

https://developer.mozilla.org/en-US/docs/Web/API/Performance