Skip to content
Advertisement

Return JavaScript class value instead of object reference

I would like to know if there is a way to return a JS class’s value by default instead of of reference to the class object itself. Let’s say, for example, I want to wrap a string..

var StringWrapper = function(string) {
    this.string = string;
};

StringWrapper.prototype.contains = function (string) {
    if (this.string.indexOf(string) >= 0)
        return true;
    return false;
};

var myString = new StringWrapper("hey there");

if(myString.contains("hey"))
   alert(myString); // should alert "hey there"

if(myString == "hey there") // should be true
   doSomething();

and now I want to get string just by using myString rather than myString.string. Is this doable somehow?

Edit

I took the console.log(myString) out of the question, because console.log has behavior that I didn’t originally take into account. This question isn’t about log.

Advertisement

Answer

Your question doesn’t entirely make sense, but it kind of sounds like you want to implement the .toString interface:

var MyClass = function(value) {
  this.value = value;
};

MyClass.prototype.toString = function() {
  return this.value;
};


var classObj = new MyClass("hey there");

snippet.log(classObj);
snippet.log(classObj + "!");
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

With ES6 class syntax:

class MyClass {
    constructor(value) {
        this.value = value;
    }

    toString() {
        return this.value;
    }
}

var classObj = new MyClass("hey there");

console.log(classObj);
console.log(classObj + "!");   
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement