我有一个任务:
var s = new MyString('hello');
之后变量 s 应该返回字符串“hello”而不是内部带有“hello”的对象,如下所示:
s[0] === 'h'
如何在 JavaScript 中做到这一点?
此任务的主要目标是编写我自己的 String 类实现。
最佳答案
您可以使用字符串扩展您的类。
示例片段:
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());
关于javascript - 从类返回字符串 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60083662/