Reputation: 7969
I have made my custom object and I want to add a method into. I want to uppercase my values. But it is giving me [object object].Any idea how to get it done. fiddle
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)
Upvotes: 0
Views: 59
Reputation: 88
Demo here.
js code like this :
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]);
}
}
};
Is helpful for you ?
Upvotes: 1
Reputation: 239573
You just have to change your inc
function like this
checkObj.prototype.inc = function() {
for (var key in this) {
if (this.hasOwnProperty(key)) {
if (typeof this[key] === 'string') {
this[key] = this[key].toUpperCase();
}
}
}
};
and this gives me the following output
{ name: 'RAJORA', title: 'THIS IS A TEST', salary: 2000 }
Upvotes: 1
Reputation: 19423
When you call console.log()
and pass it an object like woo
, it uses woo.toString()
to get the string representation of it and print it.
woo
inherits toString()
from Object.prototype
which by default prints the string you are getting, i.e. [object object]
.
You have to override toString()
like this:
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;
}
Now you can just console.log(woo)
and it would work as expected.
Upvotes: 1