javascript - Set a number return value for an object -
i've asked similar question, , this answer, know it's possible make objects return strings when placed inside other strings. code based on answer allow object have custom string return value:
function mystring(value) { this.string = value; } mystring.prototype.tostring = function() { return this.string; } var strobj = new mystring('foo'); //>> strobj //<< mystring {string: "foo", tostring: function} //>> strobj+'' //<< "foo" //what want in addition this: //>> +strobj //<< 42
i got idea original question seeing effects of date
objects within strings. so, since there's feature of date
objects quite useful, i'd know if there's way me same thing date
objects when used in expression (being converted number):
+new date(); //1401414068943
i'd mystring
object same. i've tried continue mindset of prototype tostring
in object, although there js method convert strings, there's no method - native function - convert non-numbers strings.
so possible me 'automatic object-to-number conversion' own objects, or kind of sorcery available date
because it's native js?
i'd syntax be
var strobj = new mystring('foo', 42);
if that's possible.
i believe prototype method looking handles object numeric conversion object.prototype.valueof()
it can altered or customized altering tostring()
be aware sort of thing can considered bad style when may confuse other programmers (including @ future date) standard conversions can redefined behave differently expected.
Comments
Post a Comment