3 ms·
Please, please read http://killdream.github.com/blog/2011/10/understanding-javascript-oop/ http://killdream.github.com/blog/2011/10/understanding-javas... Prot
by jarek-foksa 15y ago
Please, please read http://killdream.github.com/blog/2011/10/understanding-javascript-oop/ http://killdream.github.com/blog/2011/10/understanding-javas...
Prototypical inheritance as of ES5 is really not that hard.
Here is the same example rewritten with prototypes: https://gist.github.com/1558929 https://gist.github.com/1558929
- deleted 15y ago[deleted]
- mattmanser 15y agoPlease, please realise most of us are not going to be able to use Object in ES5 till IE8 dies.
- mixu 15y agoWell, how about this? I'm fairly certain it's ES 3 compatible. https://gist.github.com/1559933 https://gist.github.com/1559933 The original was 28 lines, this is 36 (mostly because I like white space). I haven't ever really tried to emulate classes in JS, but this is probably how I would do it. The major difference is that this is written plain old Javascript rather than some special syntax - easier to understand.
- bmuon 15y agoFoo.prototype = new Bar() has the problem of setting the superclass' instance properties as prototype properties of the subclass. This can be solved pretty easily with something like Object.create (the first part explained here http://news.ycombinator.com/item?id=3424156 http://news.ycombinator.com/item?id=3424156). Here's a different example in 30 lines: https://gist.github.com/1032636 https://gist.github.com/1032636
- bmuon 15y agoObject.create has two parts: the "create a new object with this other object as its prototype" part and the "define properties" part. The first part can be easily reproduced in ES3 and it's the most useful part. It's really well explained in this article by Douglas Crockford http://javascript.crockford.com/prototypal.html http://javascript.crockford.com/prototypal.html.
- jayferd 15y agoThis is why Pjs is so small - it's just prototypal inheritance, with the bad parts taken out. You have to know how prototypes work to use Pjs.