Return JavaScript class value instead of object reference
I would like to know if there is a way to return the default JS class value instead of referencing 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 string
only want to get with help myString
, not myString.string
. Is it possible somehow?
Edit
I chose console.log(myString)
because it console.log
has behavior that I initially didn't take into account, which complicates the question that would not mean about log
.
source to share
Your question is not entirely clear, but it looks like you want to implement an interface .toString
:
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 + "!");
source to share