1. A question encountered in the interview, the subclass inherits the parent class. The parent class has two methods, override one of the methods. When it comes to inheritance, I definitely use combined inheritance. All methods are written on the prototype. It is ok to override methods directly on the prototypeobject of the subclass, because the properties# of the object are ##The search is based on the principle of proximity on the prototype chain. The method found first will be called.
2. The code is as follows:[javascript] view plain copy // supcalss var parent = function(name,age){ this.name = name; this.age = age; } parent.prototype.showProper = function() { console.log(this.name+":"+this.age); } var child = function(name,age){ parent.call(this,name,age); } // inheritance child.prototype = Object.create(parent.prototype); // child.prototype = new parent(); child.prototype.constructor = child;
// rewrite function child.prototype.showProper = function(){ console.log('I am '+this.name+":"+this.age); } var obj = new child('wozien','22'); obj.showProper();
Function creates an object with the proto object as the prototype object, and returns this object.
The order of searching methods: obj -> child.prototype ->parent.prototype3. Things to note: When implementing method inheritance and overriding in JS, or when creating When using class methods, they are all operated on the prototype object prototype. There is no need to consider other methods of inheriting methods. Related articles:Explanation of methods of defining classes in JS
Explanation of basic syntax and variables of JavaScript
Explanation of some basic and commonly used methods in js
The above is the detailed content of Key points to explain method rewriting in js inheritance. For more information, please follow other related articles on the PHP Chinese website!