Home > Web Front-end > JS Tutorial > body text

Analysis of constructor inheritance usage that can be used in js package_javascript skills

WBOY
Release: 2016-05-16 16:17:33
Original
1081 people have browsed it

The examples in this article describe the use of constructor inheritance that can be used in js encapsulation. Share it with everyone for your reference. The details are as follows:

Let’s take a look at the following code first

Methods used by the (YUI) library:

Copy code The code is as follows:
function extend(Child, Parent) {

 var F = function(){};
  F.prototype = Parent.prototype;
  Child.prototype = new F();
​Child.prototype.constructor = Child;
  Child.uber = Parent.prototype;
}

There is also a copy inheritance method, attribute copy:

This method is different from the previous one. Since the extension of child's prototype has been completed, there is no need to reset the child.prototype.constructor property because it will no longer be overwritten.

Compared with the previous method, this method is obviously slightly less efficient. Because what is performed here is to copy the prototypes of the sub-objects one by one. Rather than a simple prototype chain query.

This method is only applicable to objects containing only basic data types. All object types, including functions and arrays, are not copyable and they only support reference passing.

Copy code The code is as follows:
function extend2(Child, Parent) {
  var p = Parent.prototype;
  var c = Child.prototype;
  for (var i in p) {
   c[i] = p[i];
   }
  c.uber = p;
}

var Shape = function(){}
var TwoDShape = function(){}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){
return this.name;
}
extend2(TwoDShape,Shape);
var t = new TwoDShape();
t.name
//-->"shape"
t.toString();
//-->"shape"
TwoDShape.prototype.name = 'TwoDShape';
t.name
//-->"2d shape"
t.toString();
//-->"2d shape"

TwoDShape.prototype.toString === Shape.prototype.toString
//-->true
TwoDShape.prototype.name === Shape.prototype.name
//-->false

I hope this article will be helpful to everyone’s JavaScript programming design.

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