Skip to content Skip to sidebar Skip to footer

Create A "default" Value For An Object

Now before I ask my question, let me just say that I know strings are primitive on js and I know you can't add properties to them. Just to get that out of the way before anyone bri

Solution 1:

I believe you want to override the toString() method.

getUser.prototype.toString() = function() {
    returnthis.stringRepresentation;
};

Solution 2:

As per alert's docs,

message is an optional string of text you want to display in the alert dialog, or, alternatively, an object that is converted into a string and displayed.

So, you need to override the default toString method, like this, to give represent your object in the alert.

functionmyString (value) {
    this.actualValue = value;
}

myString.prototype.toString = function() {
    console.log("Inside myString.toString, returning", this.actualValue);
    returnthis.actualValue;
};

functiongetUser() {
    var myUser = newmyString("Bruce Wayne");
    myUser.extraData = "I am BatMan!";
    return myUser;
}

alert(getUser());

Demo

As per the toString docs,

Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString() returns "[object type]", where type is the object type.

So, this new function, which we defined, will be called even in the expressions where you use the object like a string. For example,

console.log("The value of the Object is " + getUser());

Solution 3:

Well you can actually add properties to strings, like this

String.prototype.foo=function(bar){
    returnthis+bar;
}

var str="hello, ";
alert(str.foo("world!"));

So I think what you might want be something like this

myObj={foo:"bar","hello":world,toString:function(){
    returnthis.foo+", "+this.world;
}};

and then instead of printing your myObj, you can print out myObj.toString()

Or in your case, something like this

getUser.prototype.toString=function(){
    returnthis.defaultVal+this.extraData.userPoints[index]
}

Post a Comment for "Create A "default" Value For An Object"