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..
JavaScript
x
18
18
1
var StringWrapper = function(string) {
2
this.string = string;
3
};
4
5
StringWrapper.prototype.contains = function (string) {
6
if (this.string.indexOf(string) >= 0)
7
return true;
8
return false;
9
};
10
11
var myString = new StringWrapper("hey there");
12
13
if(myString.contains("hey"))
14
alert(myString); // should alert "hey there"
15
16
if(myString == "hey there") // should be true
17
doSomething();
18
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:
JavaScript
1
13
13
1
var MyClass = function(value) {
2
this.value = value;
3
};
4
5
MyClass.prototype.toString = function() {
6
return this.value;
7
};
8
9
10
var classObj = new MyClass("hey there");
11
12
snippet.log(classObj);
13
snippet.log(classObj + "!");
JavaScript
1
2
1
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
2
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
With ES6 class syntax:
JavaScript
1
15
15
1
class MyClass {
2
constructor(value) {
3
this.value = value;
4
}
5
6
toString() {
7
return this.value;
8
}
9
}
10
11
var classObj = new MyClass("hey there");
12
13
console.log(classObj);
14
console.log(classObj + "!");
15