In traditional object-oriented programming languages, a special syntax for subclass access to parent classes is provided. Citations We often need additional assistance from parent classes when implementing subclass methods. In this case, the subclass usually calls the same name method in the parent class to finally do the work.
Although JavaScript does not have a special syntax similar to the above, we can create one!
function her(){};her.prototype.name = 'Anna';her.prototype.toString = function(){var const = this.constructor;return const.uber ? this.const.uber.toString() + ',' + this.name : this.name;}function his(){};var F = function(){};F.prototype = her.prototype;his.prototype = new F(); his.prototype.constructor = her;his.uber = her.prototype;his.prototype.name ='Jock';function child(width, height){this.width = width;this.height = height;}var F = function(){};F.prototype = his.prototype;child.prototype = new F();child.prototype.constructor = child;child.uber = his.prototype;child.prototype.name = 'Los';child.prototype.getArea = function(){return this.width * this.height;}In the process of building a relationship, we introduce an uber attribute and point it to the parent and object.
Here we updated the following:
1. Set the usber attribute to a reference to the parent object;
2. The toString() method has been updated;
The previous toString() method simply returned this.name. Now we have added an additional task to it, which is to check this.constructor.usber property, and call the toString() method of this property if it exists.
Since this.constructor itself is a function, and this.constructo.usber is a reference to the parent prototype of the current object, when we call the toString() method of the child entity, the toString() method on its prototype chain will be called.
var my = child(1,2);my.toString() // Anna, Jock, Los
The above is a detailed explanation of how children objects access parent objects introduced by the editor of JavaScript introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!