Home > Web Front-end > JS Tutorial > Key points to explain method rewriting in js inheritance

Key points to explain method rewriting in js inheritance

亚连
Release: 2018-05-17 09:57:41
Original
2453 people have browsed it

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;
Copy after login
// rewrite function  
child.prototype.showProper = function(){  
    console.log('I am '+this.name+":"+this.age);  
}  
var obj = new child('wozien','22');  
obj.showProper();
Copy after login

In this way, the subclass overrides the showProper method of the parent class. Among them, Object.create(proto)

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.prototype

3. 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template