JS inheritance usage instance analysis and js inheritance instance analysis

Source: Internet
Author: User

JS inheritance usage instance analysis and js inheritance instance analysis

This article analyzes the usage of JS inheritance. Share it with you for your reference. The specific analysis is as follows:

Inheritance: Child classes do not affect the parent class. Child classes can inherit some features of the parent class (code reuse)

Property inheritance: call the constructor call of the parent class

Method inheritance: for in: Copy inheritance (jquery also uses copy inheritance extend)

1. Copy inheritance

Function Person (name) {this. name = name;} Person. prototype. showName = function () {alert (this. name);} function Worker (name, job) {Person. call (this, name); this. job = job;} extend (Worker. prototype, Person. prototype); // If Worker is used. prototype = Person. prototype causes reference of the same problem function extend (obj1, obj2) {for (var I in obj2) {obj1 [I] = obj2 [I]} var coder = new Worker ('magicfly ', 'frontend'); coder. showName ();

2. class inheritance

Function Person (name) {this. name = name;} Person. prototype. showName = function () {alert (this. name);} function Worker (name, job) {Person. call (this, name); this. job = job;} // Worker. prototype = new Person (); // This inheritance will inherit the unnecessary attribute function F () {}; F. prototype = Person. prototype; Worker. prototype = new F (); // It is solved by creating a temporary constructor, also known as the proxy function var coder = new Worker ('magicfly ', 'start'); coder. showName ();

3. Prototype inheritance

Var a = {name: 'xiaoming '}; var B = cloneObj (a); B. name = 'xiaoqiang'; // alert (B. name); alert (. name); function cloneObj (obj) {var F = function () {}; F. prototype = obj; return new F ();}

Applicability

Copy inheritance
Class inheritance: new Constructor
Prototype inheritance: objects without new

I hope this article will help you design javascript programs.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.