javascript - 将方法添加到字符串变量的原型(prototype)

标签 javascript prototype-chain

预期:当使用 createGreetable 创建变量时,它应该具有由 greetable(text) 设置的附加属性 greet。通常的 string 方法应该仍然可以在此变量上调用。

我尝试过的:

const greetablePrototype = {
  greetable: function(greeting) {
    this.greet = `${greeting}, ${ this.valueOf() }!`
  }
}

function createGreetable(str) {
  const result = new String(str);
  Object.setPrototypeOf(result, greetablePrototype)
  return result;
}

const t = new createGreetable("world");
t.greetable("hello");
console.log(t.greet);

console.log(t.length);

输出:

hello, [object String]!
5

预期输出:

hello, world!
5

最佳答案

您可以扩展字符串类:

class Greetable extends String {
  greet (greeting) {
    return `${greeting}, ${this}!`;
  }
}

const g = new Greetable('world');
g.greet('hello'); // hello, world!
g.length // 5

关于javascript - 将方法添加到字符串变量的原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69473535/

相关文章:

javascript - 旋转标签 nvd3 折线图

javascript - 什么时候可以调用对象原型(prototype)链上的方法?

javascript - 如何使用 JavaScript 原型(prototype)在实例之间共享属性

javascript - 为什么改变对象的 [[prototype]] 会降低性能?

javascript - Function 和 Function.prototype 的区别

javascript - 检测表单何时来自灯箱或直接来自页面

javascript - Ember.js 如何拦截和过滤传递给 Ember.Object.create(params) 的参数

javascript - 为什么我的自定义验证器不会触发?

javascript - 即使没有内容,如何将侧边栏和内容扩展到全高

javascript - 将嵌套对象更改为同一个对象,其值是对象是父对象为原型(prototype)的对象