I need to achieve the following behavior:
So when creating a class instance via new, I received a string, not a class object. How to implement this? Is it even possible?
For example
class ExampleClass{
constructor(str) {
this.str = str;
}
// some code I guess...
}
const str = new ExampleClass('example')
console.log(str) // 'example'
Give this a try:
class ExampleClass extends String {}
While using Class with new it create this instance internally and return it
HOW IT WORK INTERNALLY
let ExampleClass = function(_str){
//this = Object.create(ExampleClass.prototype);
this.str = _str
// return this;
}
str = new ExampleClass('EXAMPLE');
Good practice: Can create helper function or getters instead of changing implementation
class ExampleClass{
constructor(str) {
this._str = str;
}
// some code...
get str(){return this._str;}
set str(str){this._str = str;}
helperFetchStr(){ return this._str;}
}
new ExampleClass('EXAMPLE1').str;
new ExampleClass('EXAMPLE2').helperFetchStr();
Extending the String class. Here prototype will be from string enabling you to perform all string operations directly on str
let similar = new String("EXAMPLE")
class ExampleClass extends String {
constructor(str) {
super(str);
}
// some code...
}
const str = new ExampleClass('EXAMPLE');
//console.log(str.{STRING_OPERATIONS})