Javascript Module Pattern 使用 Prototype 创建多个实例

标签 javascript jquery html performance

我想要完成的事情:使用 javascript 中的原型(prototype)创建模块,以便用户可以多次实例化一个模块,每次都使用不同的选项。

问题:当使用 var my_module3 = new module(); 然后尝试使用 my_module3.init({ option: "value "}); 不会每次都改变对象,它只改变一次。

测试:当使用 console.log 时,我们可以看到它打印出具有相同选项的两个对象,即使它们的设置不同

Object {first: "Barry", second: "Larry", third: "Sam"} 
Object {first: "Barry", second: "Larry", third: "Sam"} 

这是我的 jsFiddle 完整代码: http://jsfiddle.net/11bLouc8/2/

        var module = (function () {
        // default options
        var options = {
            first: "test",
            second: "test2",
            third: "test3"
        };
        // take in useroptions and replace default options
        var module = function(userOptions) {
            if (userOptions != null && userOptions != undefined
                && userOptions != 'undefined') {
                for (var opt in options) {
                    if (userOptions.hasOwnProperty(opt)) {
                        options[ opt ] = userOptions[ opt ];
                    }
                }
            }
        };

        //prototype
        module.prototype = {
            init: module,
            options: options
        };

        return module;

    })();

    // create a new instance
    var my_module3 = new module();
    my_module3.init({
        first: "Mike",
        second: "Lisa",
        third: "Mary"
    });

    // another instance
    var my_module2 = new module();
    my_module2.init({
        first: "Barry",
        second: "Larry",
        third: "Sam"
    });

最佳答案

函数本身的属性表现得像 static 类成员(函数的属性,而不是实例的属性)
函数原型(prototype) 的属性在不同的实例中是不同的:

function test(){};
test.prototype = {
    constructor : test,
    first : '',
    second : '',
    third : '',
    init : function(f, s, t){
        this.first = f;
        this.second = s;
        this.third = t;
        return this;
    },
    formatToString : function(){
        return 'first : ' + this.first + ', second : ' + this.second + ', third : ' + this.third;
    }
}
var t1 = new test().init(1, 2, 3);
var t2 = new test().init(4, 5, 6);
console.log(t1.formatToString());//outputs "first : 1, second : 2, third : 3"
console.log(t2.formatToString());//outputs "first : 4, second : 5, third : 6" 

关于Javascript Module Pattern 使用 Prototype 创建多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26427639/

相关文章:

html - Nivo Slider 不适用于 IE7

javascript - 在javascript中循环以 append 一系列div

javascript - Array.filter 破坏 safari 打印

html - 如何用 HTML/CSS 获得这种文字环绕效果?

javascript - PHP函数与jquery按类动态随机插入记录

jquery - 复选框始终选中自定义样式

html - div 的背景颜色/图像展开整个页面,但内容保留在包装器中

javascript - 如何在多级数组中选择对象

javascript - JS : regex for numbers and spaces?

javascript - angular2 Material 复选框是否选中