简体   繁体   中英

Javascript - create a new object that mimics primitive data type

I need to create an new Object in Javascript which should return a number value. What I expect is:

 var Currency = function(args) { return args*Currency.prototype.multiple; } Currency.prototype.multiple = 1000; Currency.prototype.Locale='en-IN'; Currency.prototype.currency= 'INR'; Currency.prototype.paise = function(){ return (Currency.prototype.args*Currency.prototype.multiple); }; Currency.prototype.show = function(){ return (this.valueOf()/Currency.prototype.multiple).toLocaleString(Currency.prototype.Locale, { style: 'currency', currency: Currency.prototype.currency }); }; var num = new Currency(5); console.log(num) //5000 

But what I got is a object

currency{}

How to achieve my intended result?

When you create an instance with new it automatically returns the newly created object from constructor. It is not recommended to override it unless you are sure about it. Also note that if you return a non-object like a number it will override that and just return the newly created object. If you want to override this you will have to return an object itself, like return {value: args*Currency.prototype.multiple} but you have to add your logic to keep reference to your newly created object to use later, like accessing the currency .

In your case, you can just have a value for each currency and set it in constructor which you can later access with myObject.value

To use it as number when it demands use as a number you can use valueOf as @Xufox mentioned

With the preceding code(valueOf) in place, any time an object of type myNumberType is used in a context where it is to be represented as a primitive value, JavaScript automatically calls the function defined in the preceding code.

var num = new Currency(5);
console.log(num+100 + num.currency);//5100INR

 var Currency = function(args) { this.value = args*Currency.prototype.multiple; } Currency.prototype.multiple = 1000; Currency.prototype.Locale='en-IN'; Currency.prototype.currency= 'INR'; Currency.prototype.paise = function(){ return (Currency.prototype.args*Currency.prototype.multiple); }; Currency.prototype.show = function(){ return (this.valueOf()/Currency.prototype.multiple).toLocaleString(Currency.prototype.Locale, { style: 'currency', currency: Currency.prototype.currency }); }; Currency.prototype.valueOf = function(){ return this.value; } var num = new Currency(5); console.log(num.value + num.currency) //5000 console.log(num+100 + num.currency); var num2 = new Currency(50); console.log(num2.value + num2.currency) //5000 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM