繁体   English   中英

Javascript-创建一个模仿原始数据类型的新对象

[英]Javascript - create a new object that mimics primitive data type

我需要在Javascript中创建一个新对象,该对象应返回一个数字值。 我期望的是:

 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 

但是我得到的是一个对象

currency{}

如何达到我的预期结果?

使用new创建实例时,它将自动从构造函数中返回新创建的对象。 除非您确定,否则不建议覆盖它。 还要注意,如果您返回一个非对象(如数字),它将覆盖该对象,并仅返回新创建的对象。 如果要覆盖此方法,则必须返回一个对象本身,例如return {value: args*Currency.prototype.multiple}但必须添加逻辑以保留对新创建对象的引用,以供以后使用,例如访问currency

在您的情况下,您可以为每种货币设置一个value ,然后在构造函数中进行设置,以后可以使用myObject.value访问

要在需要使用数字时将其用作数字,可以使用valueOf,如@Xufox所述

使用前面的代码(valueOf),只要在上下文中使用myNumberType类型的对象(将其表示为原始值),JavaScript就会自动调用前面的代码中定义的函数。

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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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