I wonder how is it possible to create an object for example MyObject() which it can act like javascript Date object when we +(new MyObject()) like:
var a = new Date();
alert(+a);
Your object needs to have a valueOf method like so:
var f=new function(){
this.valueOf=function(){
return 5;
}
};
alert(+f); // Displays 5
If you don't want to define the method on the object but on its prototype as the comments suggested, use the following:
function MyObject(value){
this.value = value;
}
MyObject.prototype.valueOf = function(){
return this.value
}
var o = new MyObject(17);
alert(+o); // Displays 17
valueOf on the prototype. +1 otherwise.valueOf method. Actually, my example uses a constructor (without a name) to create a valueOf method per object. You could have created the method within the prototype to share it across instances but I wanted to keep it as simple as possible and use a constructor.Create a function, which changes the this property. After defining the function using function(){}, add methods to it using prototype.
Normally, an instance of a function created using the new keyword will return an Object, which reprsents the this inside the defined function. When you define a toString method, the function will show a custom string when called from within a string context (default [object Object].
Example:
function MyClass(value){
this.value = value
this.init_var = 1;
}
MyClass.prototype.getInitVar = function(){
return this.init_var;
}
MyClass.prototype.setInitVar = function(arg_var){
this.init_var = arg_var;
}
MyClass.prototype.toString = function(){
return "This class has the following property: " + this.init_var;
}
var class_instance = new MyClass();
class_instance.setInitVar(3.1415);
alert(class_instance)
toString is called when valueOf doesn't exist. Augustus's solution isn't portable, as it does not make use of prototypes.valueOf for this purpose. Regarding portability it should not matter if you define the method on an object directly or on its prototype. I would be interested to learn which portability issues can arise because I can't think of any.Here is the solution,
var MyObject = Date;
var b= new MyObject();
alert(+b) //It will display the current date in milliseconds;
Hope this helps you.
Date.