2017-02-19 57 views
0

我需要在Javascript中創建一個新對象,該對象應返回一個數字值。 我想到的是: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{} 

如何實現我想要的結果?

+0

請提供更多的上下文。你究竟想要做什麼? –

+1

你的代碼有點奇怪,如果你省略'new'關鍵字,你可以避免創建一個對象。只需要調用'貨幣'就像一個正常的功能。 – Scarysize

+0

@FelixKling我想創建一個新的數據類型'貨幣',它有自己的屬性。貨幣總是一個數字,但它應該乘以1000.我不想訪問使用obj.value函數的值。相反,我想通過簡單的obj來訪問它的值(像原始數據類型) – Avinash

回答

0

當您使用new創建實例時,它會自動從構造函數返回新創建的對象。除非您確定,否則不建議覆蓋它。另請注意,如果您返回一個非對象,如數字,它將覆蓋該對象,並返回新創建的對象。如果你想覆蓋這個,你將不得不返回一個對象本身,比如return {value: args*Currency.prototype.multiple},但是你必須添加你的邏輯來繼續引用你新創建的對象以便稍後使用,比如訪問currency

在你的情況,你可以爲每個貨幣value並設置它在構造函數中,你可以當它需要使用一個號碼,您可以使用valueOf像下文中myObject.value

訪問要使用它作爲數@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

+0

謝謝:)我希望對象的行爲作爲本機數據類型。即,而不是'num.value'來訪問我的值我希望'num'本身來存儲我的數據(如原始數據類型)。 – Avinash

+1

@Avinash你可以在'prototype'上定義一個返回值的'valueOf'函數屬性。 'num'將仍然是一個對象,但是您可以將它用作數字。 – Xufox

+0

@Xufox這是一個好主意:) – sabithpocker

相關問題