JS Inheritance Usage Example Analysis _javascript skill

Source: Internet
Author: User

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

Inheritance: Subclasses do not affect the parent class, and subclasses can inherit some of the functions of the parent class (code reuse)

Inheritance of a property: Calling the constructor of the parent class call

Method inheritance: For in: Copy Inheritance (jquery is also a copy-inherited 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 you use Worker.prototype=person.prototype, it will cause references to 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 inherits the unnecessary property 
function F () {} of the parent;
F.prototype = Person.prototype;
Worker.prototype = new F ();
Solved by establishing 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 = ' Xiao Qiang ';
alert (b.name);
alert (a.name);
function Cloneobj (obj) {
  var F = function () {};
  F.prototype = obj;
  return new F ();
}

Applicable situation

Copy inheritance: A generic type that has new or no new is available
Class Inheritance: New constructor
Prototype inheritance: An object without new

I hope this article will help you with your JavaScript programming.

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.