Core JavaScript 1.5 Reference:Global Objects:Object: noSuchMethod
From MDC
Non-standard
Contents |
[edit] Summary
Executes a function when a non-existent method is called on an object.
[edit] Syntax
obj.__noSuchMethod__ = fun
[edit] Parameters
-
fun - a function that takes the form
-
function (id, args) { . . . }-
id - the name of the non-existent method that was called
-
args - an array of the arguments passed to the method
-
[edit] Description
By default, an attempt to call a method that doesn't exist on an object results in a TypeError being thrown. This behavior can be circumvented by defining a function at that object's __noSuchMethod__ member. The function takes two arguments, the first is the name of the method that was attempted to call and the second is an array of the arguments that were passed in the method call. The second argument is an actual array (that is, it inherits through the Array prototype chain) and not the array-like arguments object.
If this method cannot be called, either as if undefined by default, if deleted, or if manually set to a non-function, the JavaScript engine will revert to throwing TypeErrors.
obj.methodName()). See bug 371033.[edit] Examples
[edit] Example: A basic usage of __noSuchMethod__
Suppose you have a project which has deprecated the use of an errorize method , both because errorize is poorly-named and because your new log method handles the severity of the occurrence, such as an error versus a simple warning. You could replace the functionality of errorize using __noSuchMethod__ to substitute a call to log:
wittyProjectName.log = function log (message, type) {
if (type == 0) {
// log an error
}
else if (type == 1) {
// log a warning
}
}
wittyProjectName.__noSuchMethod__ = function __noSuchMethod__ (id, args) {
if (id == 'errorize') {
wittyProjectName.log("wittyProjectName.errorize has been deprecated.\n" +
"Use wittyProjectName.log(message, 0) instead.", 1);
wittyProjectName.log(args[0], 0); // log the message to the error log
}
}