As mentioned above, JavaScript Object-oriented implementation must be able to implement inheritance. Although many js frameworks help us implement the inheritance function, or we cannot use the inheritance of js in our daily work and study, but we still need to know about inheritance in js to help us read how inheritance is implemented in the Framework. In the following article, I will simulate the inheritance implementation in js.
First, let's take a look at one of the following methods to create an object:
/** Object factory */function objectFactory (jsonObj) {function objectEntity () {} if (typeof jsonObj = "object") {for (var index in jsonObj) {objectEntity. prototype [index] = jsonObj [index] ;}return objectEntity;} var Person = objectFactory ({pname: 'andy ', sex: 'man '}); var person = new Person (); console.info (person + "--" + Person); // [object Object] -- function objectEntity () {} console.info (person. pname); console.info (person. sex );ObjectFactory accepts a json object jsonObj as the parameter. In this function, an objectEntity function is created, and then the input jsonObj is determined.
Whether it is an object type. If yes, it will traverse the json object and append each retrieved value to the prototype of objectEntity. Note that
It is objectEntity (you can refer to the js closure concept in the previous section), that is to say, Person points to objectEntity, then the Person prototype is naturally above
Pname, sex, and other attributes.
If we can understand the above, we can implement the next inheritance (similar to the inheritance underlying implementation in many frameworks)
/** Inherit */function inherit (obj, prop) {function f () {} if (typeof obj = "object") {for (var index in obj) {f. prototype [index] = obj [index] ;}} else {f. prototype = obj. prototype; for (var index in prop) {f. prototype [index] = prop [index] ;}} return f ;}var Animal = inherit ({type: 'animal ', name: 'animal', jump: 'jup'}); var Dog = inherit (Animal, {name: 'I am a dog', jump: 'dog jumpping'}); var dog = new dog; console.info (dog. type); console.info (dog. name );
Here, we will not explain the inherit function in detail. Readers can analyze it on their own. Here, Dog inherits Animal, then, the Dog object created by dog naturally has various attributes in Animal.