[寄生构造函数]扩展原类

例子一

假设我们想创建一个具有额外方法的特殊数组。

由于不能直接修改Array构造函数(此为使用寄生构造函数模式的原因)

function SpecialArray() {

    // 创建数组
    var values = new Array();

    // 添加值
    // values.push.apply(values, arguments);
    values.push(...arguments);

    // 添加方法
    values.toPipedString = toPipedString

    // 返回数组
    return values;
}

function toPipedString () {
    return this.join("|");
}

var colors = new SpecialArray("red""blue""green");
console.log(colors.toPipedString()); // console: "red|blue|green"

当然,对于使用new关键字来创建对象的构造函数,我们要扩展其方法,更为简便的方法是直接使用继承

class SpecialArray extends Array {
    toPipedString () {
        return this.join("|")
    }
}

var colors = new SpecialArray("red""blue""green");
console.log(colors.toPipedString()); // console: "red|blue|green"
例子二

对象实例的原始方法不好用, 我们想为之创建更简洁的方法

function SpecialRaphael (id{
    var r = Raphael(id)
    r.easy_circle = circle
    return r
}

function circle (options{
    options = options || {}
    return this.circle(options.cx, options.cy, options.r)
        .attr({
            "fill": options.fillColor,
            "stroke": options.strokeColor,
            "stroke-width": options.strokeWidth
        })
        .translate(options.x || 0, options.y || 0)
}

// ---应用---
// 原始画圆
// var paper = Raphael('element', 500, 500)
// var circle = paper.circle(300, 300, 50).attr({
//     "fill":"red",
//     "stroke":"blue",
//     "stroke-width":2
// });

// 现在画圆
var paper = SpecialRaphael('element'500500)
var circle = paper.easy_circle({
    cx300,
    cy300,
    r50,
    fillColor"red",
    strokeColor"blue",
    strokeWidth2,
})
原文地址:https://www.cnblogs.com/rencoo/p/10816838.html