[英]How to create a javascript object like Date()?
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: 我想知道如何创建一个对象,例如MyObject(),当我们+(new MyObject())
时,它可以像javascript Date对象一样工作:
var a = new Date();
alert(+a);
Your object needs to have a valueOf
method like so: 您的对象需要有一个valueOf
方法,如下所示:
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: 如果不想按注释建议在对象上而是在其prototype
上定义方法,请使用以下方法:
function MyObject(value){
this.value = value;
}
MyObject.prototype.valueOf = function(){
return this.value
}
var o = new MyObject(17);
alert(+o); // Displays 17
Create a function, which changes the this
property. 创建一个函数,此函数将更改this
属性。 After defining the function using function(){}
, add methods to it using prototype
. 使用function(){}
定义函数后,请使用prototype
向其添加方法。
Normally, an instance of a function created using the new
keyword will return an Object, which reprsents the this
inside the defined function. 通常,使用new
关键字创建的函数的实例将返回一个Object,该Object表示已定义函数中的this
。 When you define a toString
method, the function will show a custom string when called from within a string context (default [object Object]
. 定义toString
方法时,从字符串上下文(默认为[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)
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. 希望这对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.