The inheritance between JS objects discards the concept of the prototype and the constructor, and inherits the way the attribute is copied between the literal objects.
First, let's write a well-encapsulated inheritance function:
function Extend (parent) { var child={}; for (var in parent) { Child[i]=parent[i]; } Child.uber=parent; return Child ;}
The function has an argument parent, a new empty child object inside the function, which, like a white artboard, gradually copies the contents of the parent object. The For loop is a copy of the properties and methods in the parent object to the child object. Uber on the sub-object points to the parent object, so that the Uber property called the child object can call the parent object's properties and methods, which is quite the same as the super in Java, why JS is not super, because super in JS is reserved words, so the use of German and "super" Synonymous with "Uber" instead.
Here's a look at the actual application of this function, first creating a Parent object:
var shape={ color:"Blue", Name:"Shape", getName:function() { return This . Name;} }
We then implement the inheritance and some methods of extending and overriding the child objects:
var circle=extend (Shape); circle.name = "Circle" ;circle.getname =function () { return "ParentName:" +this . Uber.getname () + "ChildName:" +this .name;} Circle.gets =function () { return this . Radius*3.14 =function (RADIUS) { this . Radius=radius;}
First use the Extend function to implement inheritance
The child object adds a new Name property and a new GetName method, as well as an extended get method and init initialization method
GetName This.uber.getName () calls the parent object's GetName () method, gets the Name property of the parent object, and THIS.name gets its own name property.
Next, execute the method:
Circle.init (5); Console.log (Circle.name+ "," +circle.uber.name); Console.log (Circle.getname ()+ ", "+Circle.uber.getName ()); Console.log (Circle.gets ()); /* results: Circle,shapeparentname:shape childname:circle,shape78.5 */
The inheritance between JS objects