原文:http://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/
I thought I quite ‘understood’ inheritance in JavaScript until I got flummoxed while trying to test my understanding. The JS prototypical inheritance model is hugely different from the classical approaches of the languages I started out with; the only way to fix this that I know of is by writing code and after spending hours screaming at my console I finally saw the light Alhamdulilah.
JS is a weakly-typed prototypical language and thus classes aren’t really ‘classes’; instead they are functions which are in turn objects. New objects are created from constructor functions by using the new keyword and this allows you to kind of ‘simulate’ OOP. But mind you; its inheritance model is still different.
Some sample code that shows this difference between static and instance properties. All object properties are public although can easily make them private by declaring them with var (I added an example); for these private properties you’ll have to add accessors and setters; read this for an explanation of closures and this pattern.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
|
It’s interesting to see that static fields cannot be accessed from child context in JavaScript (which makes sense); Java, however, allows static fields to be accessed from object context; this is kinda weird as the objects don’t really ‘have’ that variable.
Here’s a quote from the Java Tutorials website:
Note: You can also refer to static fields with an object reference like
myBike.numberOfBicyclesbut this is discouraged because it does not make it clear that they are class variables.
One tip: don’t just read code and assume you understand it. Sure, you can always convince yourself that you ‘know’ it. However, if you really want to KNOW it then read it, write it and then try extend it (if you have the time and enthusiasm).
So, what other differences do you know between classical and prototypical inheritance?
Related articles
- The language series: JavaScript (abdulapopoola.wordpress.com)
- JavaScript, functional programming aspects