2

I'm trying to work out someone else's code and I'm really stuck on how they've managed to do this. The code is very long so I'll try and give a simplistic example of what I'm trying to find out.

I have something like the following:

var obj = function(){
this.obj1 = "test1";
this.obj2 = "test2";
};

var inst = new obj;
alert(inst);

This outputs [object]. What I would like to know how to do, is to make the value of this return "test1" instead - BUT also still enable me to call the object members such so that I could also do

alert(inst.obj2);

And get an output: 'test2'.

The way I thought I could do it was something like:

var obj = function(){
    this.obj1 = "test1";
    this.obj2 = "test2";
    return this.obj1;
};

var inst = new obj;
alert(inst);

but this also returns [object]

This is what the code I am trying to decipher seems to be doing. The syntax is much more complex - it uses closures and prototype I think, but I am still not getting my head around these so don't really understand what's going on.

Many thanks!

1

1 Answer 1

5

To make alert show something other than [object Object], define the .toString() method on your object.

function MyObj() {
    this.obj1 = "test1";
    this.obj2 = "test2";
};

MyObj.prototype.toString = function() {
    return this.obj1;
};

var inst = new MyObj();
alert(inst);   // will show "test1"
Sign up to request clarification or add additional context in comments.

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.