1

I'm trying, without success, to do like in other languages which the object can have a default return value, but yet has its methods. Like:

var o = {
    this: "MyReturn",
    SampleString: "My String",
    MyMethod1: function() {},
    MyMethod2: function() {},
}

Then, my output should be:

> o
< "MyReturn"
> o.SampleString
< "My String"
> o.MyMethod1()
< function() {}

Is it possible to do? (In a way that doesn't use Prototype, or it will conflict with my code)

0

3 Answers 3

2

This is not possible as-such. o would always be an object. The closest you could come would be custom toString method and casting o to a string or making the object a Function and call o like o().

Here are some option that get as close as JavaScript can get.


Option 1: Making o a function object and calling it.

var o = function(){
  return "MyReturn";
};
o.SampleString = "My String";
o.MyMethod1 = function() {};
o.MyMethod2 = function() {};

Output

> o()
< "MyReturn"
> o.SampleString
< "My String"
> o.MyMethod1()
< function() {}


Option 2: Custom toString method.

var o = {
    toString: function(){return "MyReturn";},
    SampleString: "My String",
    MyMethod1: function() {},
    MyMethod2: function() {},
}

Output

> String(o)
< "MyReturn"
> o.SampleString
< "My String"
> o.MyMethod1()
< function() {}

In this second option, String(o) can be substituted for ""+o, o.toString(), or anthing that causes type-casting to a string.

Sign up to request clarification or add additional context in comments.

Comments

1

You are looking for the toString() method.

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. Source: MDN Object.prototype.toString()

var o = {    
    SampleString: "My String",
    MyMethod1: function() {},
    MyMethod2: function() {}

};

o.toString = function () {
   return "MyReturn";
};

alert(o);
// MyReturn;

alert(o.SampleString);
// My String;

alert(o.MyMethod1);
// function () {}

JSFIDDLE

8 Comments

You might want to check the output on more time.
That is a pitty we have to use o.toString() to call the value, but it solves in parts.
alert !== console.log. And do you know why alert magically works?
@epascarello please enlighten me.
@TonyCamargo it will do that for all objects
|
0

I think the closest is this

 var o = {name:"myName"};    
 o.toString = function(){return o.name}    
 console.log(o+"");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.