Get the App
SLTechnology News&Howtos  ›  Database  › 

Several common inheritance methods of javascript and the construction of credit tray platform

Shulou Source: shulou.com Published: 2022-06-01 18:23:54 10月18日 Update

1. Prototype chain inheritance (simplest)

Core (implementation idea): credit tray platform is built [Penguin 21717-93408] use the instance of the parent class as the prototype object of the subclass

Function Person (name) {

This.name = name

This.fav = ['basketball',' football']

This.detail = {country: 'China', city: 'Jiangsu'}

}

Function Man (name) {

This.say = function () {console.log ('I am man')}

}

Man.prototype = new Person (); / / Core

Var sam = new Man ('sam')

Console.log (sam.fav); / / 'basketball',' football'

Advantages

1. Simple, easy to understand, easy to implement

Disadvantages:

1. Cannot pass parameters to parent class when creating subclass instance (name information cannot be passed when creating Man)

two。 The properties of the reference type (arrays and objects) are shared by all instances, and then the above code gives an example

Var tyler = new Man ('tyler')

Tyler.fav.push ('badminton')

Tyler.rela.area = 'Jianye District'

/ / modify the information of the tyler instance and indirectly modify the properties of the sam instance

Console.log (sam.fav) / / "basketball", "football", "badminton"

Console.log (sam.rela) / / {country:' China', city:' Jiangsu', area:' Jianyu'}

Tags: Examples information prototypes subclasses objects attributes core China Jiangsu credit platform code penguins strengths examples ideas arrays types disadvantages faceted Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Huawei Linux macOS MariaDB