Is it possible to set something of a default/fallback function for a JavaScript class?
var a = new function() {
this.b = function() {
return "B";
}
return "A";
}
In this example, I'd want to see B when executing alert(a.b()), and A for alert(a) alone.
var a = new function() {
this.toString = function() { return "Four Loko comes in 8 different flavors."; };
this.valueOf = function() { return "Four Loko comes in 8 different flavors."; };
this.b = function() { return "Added! :3"; };
}
alert(a);
alert(a.b());
If you overwrite the toString method of an object you can get it to return whatever you want.
Although you may be trying to return literal values from a constructor. You can only return objects from a constructor.
You may also want to overwrite .valueOf
Your question and your sample code are a little vague but this might be what you're looking for:
function A() {
this.b = function () {
return "Added! :3";
}
}
var a = new A();
alert( a.b() );
which would be better if you do it this way:
function A() {}
A.prototype.b = function () {
return "Added! :3";
}
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