gpt4 book ai didi

javascript - 如何使 "undefined is not a function"错误更有用?

转载 作者:数据小太阳 更新时间:2023-10-29 05:29:56 24 4
gpt4 key购买 nike

考虑这段 JavaScript 代码:

var x = new date()

// "ReferenceError: date is not defined" - useful error, hints at a typo ('D'ate)

var x = new MyClass.foo()

// "TypeError: undefined is not a function" - bad error, no hint it might be 'F'oo

错误本身是正确的,因为 MyClass 没有 foo 方法,所以 MyClass.foo 确实返回了 undefinednew 不喜欢这样。问题是这根本没有暗示用户可能拼错了方法名称。现实生活中的例子:

new Meteor.collection('foo')  // instead of:
new Meteor.Collection('foo') // c and C look alike with many fonts at small size

有没有一种可移植方法来检测对象在new gets undefined 之前没有方法> 自动传递给它? __noSuchMethod__正是我要找的,但它看起来像是一个非标准扩展。看起来像 IE doesn't support itV8 refused to implement it . Chromium 团队还 doesn't care much about implementing Proxy support .

看起来有一些支持 Proxy对于节点(参见 thisthis )并以 shim 的形式(“即将推出的 ECMAScript Reflect API 的 polyfill” 但请参阅下面的 mpm 评论)。

相关问题(这个归结为什么):

最佳答案

这个问题一年多后,V8 可能更改了错误消息

var MyClass = function() {
this.Foo = function() { console.log("Foo"); }
}

new MyClass().foo();

今天产生这个错误

Uncaught TypeError: (intermediate value).foo is not a function

与命名对象一起使用

var mc = new MyClass();
mc.foo();

更有用

Uncaught TypeError: mc.foo is not a function

与对象名称中的拼写错误一起使用也很有用:

new myClass().foo();

Uncaught ReferenceError: myClass is not defined

关于javascript - 如何使 "undefined is not a function"错误更有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21953573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com