Skip to content

Instantly share code, notes, and snippets.

@Shahor
Last active August 5, 2016 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shahor/205417aac1c0c2c9bd5b43312f5e636d to your computer and use it in GitHub Desktop.
Save Shahor/205417aac1c0c2c9bd5b43312f5e636d to your computer and use it in GitHub Desktop.
class Base {
constructor (id) {
this._id = id
}
say () {
console.log(this._id)
}
static get () {
// Oh god, this ? in static ? Javascript watayoudoin?!
return new this(`${this.prototype._name} : ${Math.random()}`)
}
}
class Hop extends Base { }
Base.prototype._name = 'base'
// The only way I found to override, since we can't have static properties
// If you know another way, please enlighten me
Hop.prototype._name = 'hop'
let base = Base.get()
, hop = Hop.get()
console.log("base is instance of Base ?", base instanceof Base)
console.log("hop is instance of Hop ?", hop instanceof Hop)
base.say()
hop.say()
// So many possibilities, but this feels so gross
@BenoitZugmeyer
Copy link

That's coherent, no magic implied :) Two things:

class Base {
    static get() { ... }
}
// is basically equivalent to
function Base() {}
Base.get = function () { ... };
// 'this' is whatever is on the left of the 'dot' operator:
var foo = function () {};
foo.bar = function () { return this; };
foo.bar(); // this === foo (the function)

So when you use this in Base.get, you get Base, and likewise for Hop.

@Shahor
Copy link
Author

Shahor commented Aug 4, 2016

@BenoitZugmeyer Yes sir, those are the conclusions I came to when experimenting.
But I just thought it was a weird choice to keep "this" in that context :)

And I don't really like that way of having to use the prototype to override static properties, but I guess it will be settled/fixed when static properties come into the language.

@Fiaxhs
Copy link

Fiaxhs commented Aug 4, 2016

/me votes for that

@Shahor
Copy link
Author

Shahor commented Aug 5, 2016

@Fiaxhs 😄

@BenoitZugmeyer
Copy link

And I don't really like that way of having to use the prototype to override static properties, but I guess it will be settled/fixed when static properties come into the language.

Stage 2 for 8 days o/ tc39/proposals@52d915b
Else use Babel :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment