Javascript object to behave differently, based on index ending: foo vs. foo()
Is it possible to construct an object in a way to return the following:
baseObject.foo; // return a string describing what foo does
baseObject.foo(); // execute the foo function
baseObject.bar; // bar description
baseObject.bar(); // execute bar
Update: JavaScript Method Overloading is close, but not quite wha开发者_如何学编程t I'm looking for.
Update2: jsfiddle (of solutions provided below).
You can overwrite the default toString
method of the function:
baseObject.foo = function () { console.log('executing foo') }
baseObject.foo.toString = function () { return 'This function outputs "executing foo"'; }
baseObject.foo
has to be a function, otherwise you won't be able to call it. The only thing you can influence is how this function is coerced to a string, by overriding its toString()
method. By default toString()
returns function source code, you can make it return something else instead.
baseObject.foo = function() {
// Do something
}
baseObject.foo.toString = function() {
return "Function does something";
}
alert(baseObject.foo);
精彩评论