Add a method to builtin String type
clarkmcc opened this issue · comments
Clark McCauley commented
I'd like to add a method to the built-in string type. Here's what I've got, and the error I am getting. First of all, is what I'm doing possible, and if so, what am I doing wrong?
runtime.Get("String").ToObject(runtime).Set("toElement", func(call goja.FunctionCall) goja.Value {
return nil
})
"foobar".toElement()
Object has no member 'toElement' at <eval>:1:26(2)
Dmitry Panov commented
You need to define the method on String.prototype, not on String.
Clark McCauley commented
@dop251 ah, thank you. I tried this and am still getting the same error, so I'm assuming I'm doing something wrong...
runtime.Get("String").ToObject(runtime).Prototype().Set("toElement", func(call goja.FunctionCall) goja.Value {
return nil
})
Dmitry Panov commented
Yes, what you're doing is String.__proto__.toElement = ...
, and you need String.prototype.toElement = ...
, i.e.
runtime.Get("String").ToObject(runtime).Get("prototype").ToObject(runtime).Set("toElement", func(call goja.FunctionCall) goja.Value {
return nil
})
Clark McCauley commented
Worked perfectly. Thanks!