Hacker News new | past | comments | ask | show | jobs | submit login

No, it's syntactic sugar for one particular approach to using prototypical inheritance that resembles "traditional" OOP.



I think one of the biggest irks for me personally when using ES6 is how `this` works.

class Foo { constructor() { this.whatever = 4; }

  bar() {
    this.whatever = 3;
  }
}

var foo = new Foo();

blah.onSomeEvent(foo.bar);

// When SomeEvent is triggered on blah, `this` will refer to blah, not foo.

console.log(blah.whatever); // 3 console.log(foo.whatever); // 4

// You have to: blah.onSomeEvent(foo.bar.bind(foo));

console.log(blah.whatever); // undefined console.log(foo.whatever); // 3

Which I know is just traditional JS, but it's a little unexpected because that's not how most OO languages operate.


Can you explain? It's sugar for this very common pattern:

    function Bar() {
      Foo.call(this);
    }

    Bar.prototype = Object.create(Foo.prototype);
    Bar.prototype.constructor = Bar;

    Foo.prototype.thing = function() { ....

What other "approach" to prototypical inheritance is there in JavaScript? The module pattern doesn't use prototypes.


This blog post and presentation discusses this in more detail. http://ericleads.com/2013/02/fluent-javascript-three-differe...


Is there a good book or website to learn about prototypical inheritance? I've read a lot of Crockford's book and some stuff online about it, but I've never run across the pattern you use above.

It would be great to know what the benefits are vs declaring function literals on an object, or declaring a function directly on Bar's prototype.


Mozilla's documentation does a good job explaining prototypal inheritance:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inhe...


My "Aha!" moment came while reading this Kyle Simpson blog series http://davidwalsh.name/javascript-objects


no, it's just syntactic sugar




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: