JavaScript has been around for nearly 20 years, but there are still different opinions on this prophecy. Many people say that JavaScript cannot be considered an object-oriented programming language. But JavaScript is very loosely typed and has no compiler. This gives programmers a lot of freedom, but also brings some flaws.
Although JavaScript is not an object-oriented language. But we can implement JavaScript's object-oriented programming by imitating the way other languages implement object-oriented programming.
The following is a very classic inheritance method in JavaScript tutorials.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
|
Although there is no big problem in executing the above method, the overall style of the code is slightly bloated and not very elegant. Properties can still be modified outside. This approach does not protect inherited properties. The following method omits new and prototype and uses the feature of "function inheritance" to implement it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
|
Warm reminder: The advantage of using prototypal inheritance is that it is memory efficient. No matter how many times it is inherited, the prototype properties and methods of the object are only saved once. When functions are inherited, duplicate properties and methods are created for each new instance. If you create many large objects, memory consumption will be very large. The solution is to save the larger properties or methods in an object and pass it as a parameter to the constructor. This way all instances will use one object resource instead of creating their own versions.
The above two methods can easily implement JavaScript object-oriented inheritance. No method is absolutely good, and no method is absolutely bad. Depends on personal preference.