[英]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.