寄生构造函数模式创建对象

这个模式可以在特殊的情况下用来为对象创建构造函数

例子一

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

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

function SpecialArray() {

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

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

    // 添加方法
    values.toPipedString = function() {
        return this.join("|");
    };

    // 返回数组
    return values;
}

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

原始库对象的方法不好用, 我们想创建具有更简便方法的对象

function SpecialRapheal(id{

    // 创建Raphael实例
    var r = Raphael(id);

    // 添加方法
    r.line = function(obj{
        return this.path(obj.path)
            .attr({"stroke": obj.strokeColor, "stroke-width": obj.strokeWidth})
            .translate(obj.x || 0, obj.y || 0);
    };

    r.rec = function(obj{
        return this.path(obj.path)
            .attr({"stroke": obj.strokeColor, "fill": obj.fillColor})
            .translate(obj.x || 0, obj.y || 0);
    };

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

    return r;
}

猜你喜欢

转载自www.cnblogs.com/rencoo/p/10816838.html