go2js icon indicating copy to clipboard operation
go2js copied to clipboard

Suggestion: add local aliasing for this

Open egonelbre opened this issue 12 years ago • 5 comments

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.

egonelbre avatar Nov 17 '12 02:11 egonelbre

Could you add an example with an anon. function where it fails?

tredoe avatar Nov 17 '12 10:11 tredoe

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.

egonelbre avatar Nov 17 '12 15:11 egonelbre

+1 on this proposal, although perhaps the aliased name should be underscored prefixed (e.g. "var _this = this;")

coopernurse avatar Jan 04 '13 17:01 coopernurse

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.

egonelbre avatar Jan 04 '13 21:01 egonelbre

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.

coopernurse avatar Jan 04 '13 21:01 coopernurse