javascriptecmascript-6traceur

Javascript ES6 eliminate usage of 'this' keyword everywhere in classes


I am using Traceur to be able to write some javascript of the future right now and this is a function that I have in some class

create() {
    this.game.physics.startSystem(Phaser.Physics.ARCADE);

    this.segmentcache = new SegmentCache(this.game);
    this.segments = new Segments(this.game);
    this.segments.cache = this.segmentcache;
    this.segments.seek(3);

    this.guy = new Guy(this.game, 140 + 8, 80);
    this.guy.anchor.set(0.5, 1.0);
    this.game.add.existing(this.guy);

    this.game.camera.x = 100;
    this.ticks = 0;
    this.cross = 0;
}

Of course, as with any traditional javascript code, it is covered with the this keyword all over the place. Coming from Java and the likes, it is very unnatural for me to have to specify this when referring to a field inside of a class when I don't have to.

Is there any way of getting Traceur to interpret classes the same way as Java? (i.e auto insert this when not specified, etc.)


Solution

  • AFAIK, no.

    In Java, C#, C++, etc. this is a feature of compiler, not execution. This means it is done implicitly and what the compiler does is putting correct address into this and referencing variables in a correct way. There is a rule in most compilers that if you have a local variable (in local scope) with same name it has precedence of member variables.

    While in javascript you can easily substitute this via call, apply or bind and have your function being called over an object which the author didn't intend to work with (i.e. this may be an object with different structure). And I think this is the reason why the language syntax requires from you to always explicitly specify if you're referring scope or this.

    More in javascript function body actually can read global scope, so defining window.member (if in browser) may change the behavior of you functions if you don't use explicit this