Home  >  Article  >  Web Front-end  >  js封装可使用的构造函数继承用法分析_javascript技巧

js封装可使用的构造函数继承用法分析_javascript技巧

WBOY
WBOYOriginal
2016-05-16 16:17:331052browse

本文实例讲述了js封装可使用的构造函数继承用法。分享给大家供大家参考。具体如下:

先来看下面这段代码

(YUI)库所用的方法:

复制代码 代码如下:
function extend(Child, Parent) {

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

另外还有一种拷贝继承方法,属性拷贝:

这种方法与之前的不同,由于已经完成对child的原型进行扩展,不需要再重置child.prototype.constructor属性了,因为它不会再被覆盖。

与之前的方法相比,这个方法在效率上显然略孙一筹。因为这里执行的是对子对象原型的逐一拷贝。而非简单的原型链查询。

这种方式仅适用只包含基本数据类型的对象,所有的对象类型包括函数和数组,都是不可复制的,他们只支持引用传递。

复制代码 代码如下:
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

希望本文所述对大家的javascript程序设计有所帮助。

Statement:
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