Skip to content
This repository has been archived by the owner on May 1, 2024. It is now read-only.

Suggestion: add local aliasing for this #2

Open
egonelbre opened this issue Nov 17, 2012 · 5 comments
Open

Suggestion: add local aliasing for this #2

egonelbre opened this issue Nov 17, 2012 · 5 comments

Comments

@egonelbre
Copy link

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.

@tredoe
Copy link
Owner

tredoe commented Nov 17, 2012

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

@egonelbre
Copy link
Author

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.

@coopernurse
Copy link

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

@egonelbre
Copy link
Author

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.

@coopernurse
Copy link

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants