0

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)
3
  • what do you exepct from console.log(woo)? woo it's your object Commented Oct 12, 2013 at 11:41
  • checkObj { name="RAJORA", title="THIS IS A TEST", salary=2000, more...} Commented Oct 12, 2013 at 11:42
  • then console.log(JSON.stringify(woo)) (in your case) Commented Oct 12, 2013 at 11:48

3 Answers 3

1

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 }
Sign up to request clarification or add additional context in comments.

Comments

1

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.

4 Comments

Thanks it is giving desired result but it is also throwing error. jsfiddle.net/T8w49/2
thanks again. One thing i need to know What is prop. Does integer prop
@amit I have just rolled the final version of the answer, please check edit.
@amit prop is variable that would hold the name of each property on woo as it loops on it.
1

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 ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.