Reputation: 95
I have a task:
var s = new MyString('hello');
after that variable s should return string 'hello' instead of object with 'hello' inside, like this:
s[0] === 'h'
How to do this in JavaScript?
Main goal in this task is write my own String class implemantation.
Upvotes: 1
Views: 2774
Reputation: 29667
You can extend your Class with String.
Example snippet:
class MyString extends String {
constructor(str){
super(str);
}
getReverse(){
return this.toString().split('').reverse().join('');
}
}
var mystr = new MyString('hello');
console.log(mystr.toString());
console.log(mystr[0] == 'h');
console.log(mystr.getReverse());
Upvotes: 4
Reputation: 47
Well, creating object with the new keyword will only give you... an object, obviously. To return string which is built in your custom string implementation you will need something like this:
class MyString {
constructor(str){
this.content = str;
}
getString(){
return this.content;
}
}
And usage:
var s = 'hello';
var strObj = new MyString(s);
var ss = s.getString();
console.log(s == ss); //true
Thats because you constructed your object so its like a box for your string. Method getString acts like you unbox your package and receive your string back. Thats why they are equal at the moment (because neither of these changed between construction of MyString and plain string).
This method for creating getSomething is called getter, and similarly the setSomething is called setter where setter does not receive any data outside the object but sets something inside it.
Of course there is a way to modify string type too, so it can perform your tasks and hold your custom methods, but honestly i dont think this is important nor convenient to you at this moment. Nonetheless check out prototype/prototyping if you want. Good luck bro!
Upvotes: 0