dop251 / goja

ECMAScript/JavaScript engine in pure Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add a method to builtin String type

clarkmcc opened this issue · comments

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)

You need to define the method on String.prototype, not on String.

@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
})

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
})

Worked perfectly. Thanks!