我不认为有任何方法可以使用本机语法来表达这个概念,甚至可以使用Rhino/Spidermonkey专有扩展,如getter和setter:
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Objects#Defining_Getters_and_Setters
Object.prototype.invokeMethodOrDefault = function(methodName,argsArray){
if(this[methodName] && typeof this[methodName] == "function"){
//invoke method with given arguments
this[methodName].apply(this,argsArray)
}else{
this.defaultMethod.apply(this,argsArray)
}
}
//add a defaultMethod noop that can be overridden for individual subclasses
Object.prototype.defaultMethod = function(){print("In default method")}
//test it
foo = {
helloWorld:function(){
print("hello world!")
print("args:")
for(var i=0,l=arguments.length;i<l;i++){
print(arguments[i]);
}
}
}
foo.invokeMethodOrDefault("thisMethodDoesNotExist",[])
foo.invokeMethodOrDefault("helloWorld",["arg1","arg2"])
bar = {
helloWorld2:function(){
print("hello world2!")
print("args:")
for(var i=0,l=arguments.length;i<l;i++){
print(arguments[i]);
}
},
defaultMethod:function(){
print("in new default method")
}
}
bar.invokeMethodOrDefault("thisMethodDoesNotExist",[])
bar.invokeMethodOrDefault("helloWorld2",["arg1","arg2"])
打印以下内容:
In default method
hello world!
args:
arg1
arg2
in new default method
hello world2!
args:
arg1
arg2