2013-10-12 28 views
0

我已經創建了自定義對象,並且想要添加一個方法。我想大寫我的價值觀。但它給了我[對象對象]。任何想法如何完成它。 fiddle在javascript中使用自定義對象中的原型

function checkObj (name,title,salary){ 
    this.name= name; 
    this.title= title; 
    this.salary= salary; 
    } 

var woo=new checkObj("rajora","this is a test",2000); 
checkObj.prototype.inc=function(){ 
    for(i=0;i<this.length;i++){ 
    this[i]= this[i].toUpperCase(); 
    } 
    }; 
woo.inc(); 
console.log(woo) 
+0

你從'console.log(woo)'中看到了什麼? 'woo'這是你的對象 –

+0

checkObj {name =「RAJORA」,title =「THIS IS A TEST」,salary = 2000,more ...} – Carlos

+0

然後'console.log(JSON.stringify(woo))'(in你的情況) –

回答

1

你只需要改變你的inc功能這樣

checkObj.prototype.inc = function() { 
    for (var key in this) { 
     if (this.hasOwnProperty(key)) { 
      if (typeof this[key] === 'string') { 
       this[key] = this[key].toUpperCase(); 
      } 
     } 
    } 
}; 

,這給了我下面的輸出

{ name: 'RAJORA', title: 'THIS IS A TEST', salary: 2000 } 
1

當你打電話console.log(),並將它傳遞的對象像woo,它使用woo.toString()得到它的字符串表示並打印出來。

wooObject.prototype繼承toString()默認情況下,它會打印出您正在獲取的字符串,即[object object]

您必須覆蓋toString()這樣的:

checkObj.prototype.toString = function() { 
    var result = "checkObj {"; 
    for (var prop in this) { 
     if (this.hasOwnProperty(prop)) 
      result += (prop + " : " + String(this[prop]).toUpperCase() + ", "); 
    } 
    result += ("}"); 
    return result; 
} 

現在你只需console.log(woo),它會正常工作。

+0

感謝它給出了預期的結果,但它也是拋出錯誤。 http://jsfiddle.net/T8w49/2/ – Carlos

+0

再次感謝。有一件事我需要知道什麼是道具。整數支柱 – Carlos

+0

@amit我剛剛推出了最終版本的答案,請檢查編輯。 –

1

演示here

的js代碼:

function checkObj (name,title,salary){ 
this.name= name; 
this.title= title; 
this.salary= salary; 
} 

checkObj.prototype.inc=function(){ 

var self=this; 

for(var i in self){ 
    if(self.hasOwnProperty(i)){ 
     output(i); 
    } 
} 

function output(item){ 
    if(typeof self[item]==='string'){ 
     self[item]=self[item].toUpperCase(); 
     console.log(self[item]); 
    } 
} 
}; 

是對你有用嗎?

相關問題