go2js
go2js copied to clipboard
Suggestion: add local aliasing for this
This test
type test struct {
value string
}
func (t *test) get() string {
return t.value
}
Currently translates to:
function test(value) {
this.value=value
}
test.prototype.get = function() {
return this.value;
}
It would be probably better to translate into:
function test(value) {
this.value=value
}
test.prototype.get = function() {
var t = this;
return t.value;
}
If you are at some point doing anon. functions then handling of this can get quite complicated otherwise.
Could you add an example with an anon. function where it fails?
Currently it doesn't seem to support properly, but here's a simple example:
type test struct {
value string
}
func (t *test) get() func() string {
return func() string {
return t.value
}
}
func main() {
test := &test{"hello"}
fn := test.get()
fmt.Print(fn())
}
The expected output for that get
function should be:
test.prototype.get = function(){
var t = this;
return function(){
return t.value;
}
};
Otherwise when calling fn
in main
it will use the global this
.
+1 on this proposal, although perhaps the aliased name should be underscored prefixed (e.g. "var _this = this;")
Not really, it may make sense using in javascript but in a translator it's better to use the method receiver instead. You need the method receiver anyway so renaming the receiver to "this" in javascript adds nothing useful. Alternative of using the same variable name from the method receiver means that the problem basically disappears and it probably will make translation simpler.
Sorry, I didn't notice that your example used t as the receiver. Yes, given that Go has explicit receiver identifiers then go2js can safely use that.