Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement copy inheritance in js

Shulou Source: shulou.com Published: 2022-06-01 02:14:21 10月21日 Update

This article is about how js implements copy inheritance. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

The parent class code is as follows:

/ / define an animal class function Animal (name) {/ / attribute this.name = name | | 'Animal'; / / instance method this.sleep = function () {console.log (this.name +' sleeping!') ;}} / / prototype method Animal.prototype.eat = function (food) {console.log (this.name + 'eating:' + food);}; copy inheritance function Cat (name) {var animal = new Animal (); for (var p in animal) {Cat.prototype [p] = animal [p] } / / the following implementation modifies the prototype object, which will cause a single instance to modify name, which will affect the name value of all instances / / Cat.prototype.name = name | | 'Tom'; incorrect statement, the next sentence is the correct implementation this.name = name | |' Tom';} / / Test Codevar cat = new Cat (); console.log (cat.name); console.log (cat.sleep ()); console.log (cat instanceof Animal) / / falseconsole.log (cat instanceof Cat); / / true

Features:

Support for multiple inheritance

Disadvantages:

Low efficiency and high memory footprint (because you want to copy the properties of the parent class)

Cannot get methods that cannot be enumerated in the parent class (methods that cannot be enumerated, cannot be accessed using for in)

Thank you for reading! This is the end of this article on "how to achieve copy inheritance in js". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Tags: Copy method instance content prototype property more being article good practical code memory animal animal single object efficiency article feature Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Microsoft Docker OPPO Reno Huawei