Consider this JavaScript code:
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
The error itself is correct, because MyClass
doesn't have a foo
method, so MyClass.foo
does indeed return undefined
, and new
doesn't like that. The problem is this doesn't hint at all that the user might have misspelled the method name. Real-life example:
new Meteor.collection('foo') // instead of:
new Meteor.Collection('foo') // c and C look alike with many fonts at small size
Is there a portable way to detect that an object doesn't have a method before new
gets undefined
passed to it, automatically? __noSuchMethod__
is exactly what I'm looking for, but it looks like it's a non-standard extension. Looks like IE doesn't support it and V8 refused to implement it. The Chromium team also doesn't care much about implementing Proxy support.
Looks like there is some support for Proxy
for Node (see this and this) and in the form of a shim ("a polyfill for the upcoming ECMAScript Reflect API" but see mpm's comments below).
Related questions (what this one boils down to):
This is a common JavaScript error that happens when you try to call a function before it is defined. You get this error when you try to execute a function that is uninitialized or improperly initialized . It means that the expression did not return a function object.
An undefined error is when we declare a variable in the code but do not assign a value to it before printing the variable.
A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
Javascript TypeError: undefined is not an object that means you're trying to treat undefined value as an Object . ( simply: trying to get data from undefined value) you can safely ignore this error by using ? . As results[j]?.
More than a year after this question, V8 probably changed the error messages
var MyClass = function() {
this.Foo = function() { console.log("Foo"); }
}
new MyClass().foo();
Produces this error today
Uncaught TypeError: (intermediate value).foo is not a function
Used with named object
var mc = new MyClass();
mc.foo();
It is even more useful
Uncaught TypeError: mc.foo is not a function
Used with typo in object name is usefull, too:
new myClass().foo();
Uncaught ReferenceError: myClass is not defined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With