具有多个实例的 javascript 对象字面量模式

发布于 2024-09-27 01:42:18 字数 1313 浏览 3 评论 0原文

我开发了一个小 javscript 小部件,将一些嵌套的

    块转换为 Windows 资源管理器风格的浏览器。我最近了解了对象文字模式并决定尝试一下,所以我的代码的组织是这样的:

var myExplorer = {
    init : function(settings) {
        myExplorer.config = {
            $wrapper : $('#explorerCategories'),
            $contentHolder : $j('#categoryContent'),
            loadingImg : '<img src="../images/standard/misc/ajax_loader.gif" alt="loading" class="loading" />'
        }
        // provide for custom configuration via init()
        if (settings && typeof(settings) == 'object') {
            $.extend(myExplorer.config, settings);
        }

        // some more code...
    },

    createExpanderLink : function() {
        // more code
    },

    anotherMethod : function() {
        // etc
    }
}

然后在我的页面中我设置了我的资源管理器:

$j(function () {
    myExplorer.init();
}

顺便说一下,这一切都工作得很好。问题是当我想在同一页面上有多个浏览器样式小部件时。我尝试传递不同的设置:

$j(function () {
    // first instance
    myExplorer.init();

    //second instance
    var settings = {
        $wrapper : $('#explorerCategories2'),
        $contentHolder : $j('#categoryContent2')
    }
    myExplorer.init(settings);

}

但这只是覆盖了第一个实例的配置值,从而有效地破坏了它。我开始意识到对象字面量模式不是这里的方法,但我不确定是什么。任何人都可以提供任何指示吗?

I have developed a little javscript widget to turn some nested <ul> blocks into a windows explorer style browser. I have recently learnt about the object literal pattern and decided to give it a go, so the organisation of my code is something like this:

var myExplorer = {
    init : function(settings) {
        myExplorer.config = {
            $wrapper : $('#explorerCategories'),
            $contentHolder : $j('#categoryContent'),
            loadingImg : '<img src="../images/standard/misc/ajax_loader.gif" alt="loading" class="loading" />'
        }
        // provide for custom configuration via init()
        if (settings && typeof(settings) == 'object') {
            $.extend(myExplorer.config, settings);
        }

        // some more code...
    },

    createExpanderLink : function() {
        // more code
    },

    anotherMethod : function() {
        // etc
    }
}

Then in my page I set up my explorer with:

$j(function () {
    myExplorer.init();
}

This all works fine by the way. The problem is when I want to have more then one of these explorer style widgets on the same page. I tried passing in the different settings:

$j(function () {
    // first instance
    myExplorer.init();

    //second instance
    var settings = {
        $wrapper : $('#explorerCategories2'),
        $contentHolder : $j('#categoryContent2')
    }
    myExplorer.init(settings);

}

But this simply overwrites the config vales for the first instance which effectively breaks it. I'm beginning to realise that the object literal pattern isn't the way to go here but I'm not sure what is. Can anyone offer any pointers?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

爱的那么颓废 2024-10-04 01:42:18

使用函数而不是对象字面量,这样您就可以使用 new 关键字实例化小部件的多个对象。

function myExplorer(settings) {
    // init code here, this refers to the current object
    // we're not using a global object like myWindow anymore
    this.config = {
        $wrapper : $('#explorerCategories'),
        $contentHolder : $j('#categoryContent'),
        ..
    };

    // provide for custom configuration
    if (settings && typeof(settings) == 'object') {
        $.extend(this.config, settings);
    }

    this.someFunction = function() { 
        ..
    };

    this.otherFunction = function() {

    };
}

根据需要使用实例化该小部件的尽可能多的对象,

var foo = new myExplorer({ .. });
var bar = new myExplorer({ .. });
...

Use a function instead on an object literal, so you can instantiate multiple objects of the widget using the new keyword.

function myExplorer(settings) {
    // init code here, this refers to the current object
    // we're not using a global object like myWindow anymore
    this.config = {
        $wrapper : $('#explorerCategories'),
        $contentHolder : $j('#categoryContent'),
        ..
    };

    // provide for custom configuration
    if (settings && typeof(settings) == 'object') {
        $.extend(this.config, settings);
    }

    this.someFunction = function() { 
        ..
    };

    this.otherFunction = function() {

    };
}

Instantate as many objects of this widget as needed using,

var foo = new myExplorer({ .. });
var bar = new myExplorer({ .. });
...
爱的那么颓废 2024-10-04 01:42:18

这又如何呢?

var myExplorer = function(settings) {

  var o = {
    init: function() {
      this.somevalue = settings;
    },

    whatever: function() {
    }
  };

  o.init();

  return o;
};

var exp1 = myExplorer('something');
var exp2 = myExplorer('anything');

console.log(exp1.somevalue); //something
console.log(exp2.somevalue); //anything

What about this?

var myExplorer = function(settings) {

  var o = {
    init: function() {
      this.somevalue = settings;
    },

    whatever: function() {
    }
  };

  o.init();

  return o;
};

var exp1 = myExplorer('something');
var exp2 = myExplorer('anything');

console.log(exp1.somevalue); //something
console.log(exp2.somevalue); //anything
千と千尋 2024-10-04 01:42:18

使用以下代码来实现此目的,请记住“公共 API”(以便“内部”函数在“外部”可见):

var myExplorer = function() {
    var init = function(settings) {
        var config = {
            $wrapper : $('#explorerCategories'),
            $contentHolder : $j('#categoryContent'),
            loadingImg : '<img src="../images/standard/misc/ajax_loader.gif" alt="loading" class="loading" />'
        }
        // provide for custom configuration via init()
        if (settings && typeof(settings) == 'object') {
            $.extend(config, settings);
        }

        // some more code...
    },

    var createExpanderLink = function() {
        // more code
    },

    var anotherMethod = function() {
        // etc
    }

    // Public API 
    // return the functions you want to use outside of the current instance
    return {
        init : init,
        createExpanderLink : createExpanderLink,
        anotherMethod : anotherMethod
    }
}
var firstExplorer = new myExplorer();
var secondExplorer = new myExplorer();
// etc 

Use the following code to achieve this, remember about the 'public API' (so that the 'internal' function will be visible 'outside'):

var myExplorer = function() {
    var init = function(settings) {
        var config = {
            $wrapper : $('#explorerCategories'),
            $contentHolder : $j('#categoryContent'),
            loadingImg : '<img src="../images/standard/misc/ajax_loader.gif" alt="loading" class="loading" />'
        }
        // provide for custom configuration via init()
        if (settings && typeof(settings) == 'object') {
            $.extend(config, settings);
        }

        // some more code...
    },

    var createExpanderLink = function() {
        // more code
    },

    var anotherMethod = function() {
        // etc
    }

    // Public API 
    // return the functions you want to use outside of the current instance
    return {
        init : init,
        createExpanderLink : createExpanderLink,
        anotherMethod : anotherMethod
    }
}
var firstExplorer = new myExplorer();
var secondExplorer = new myExplorer();
// etc 
萌酱 2024-10-04 01:42:18

当您像这样调用 $.extend() 时,它会合并将第二个对象的属性合并到第一个对象中:

$.extend(myExplorer.config, settings);

相反,创建一个新对象,它是合并的结果,而第一个对象(默认值)保持不变,如下所示:

this.settings = $.extend({}, myExplorer.config, settings);

这仍然是将传递的对象合并到第一个,但第一个是一个新对象 ({}),因此我们不会影响其他任何一个,然后只需使用 this.settings (或不同的名称以使其绝对清晰)在您的对象内。

When you call $.extend() like this, it merges the second object's properties into the first:

$.extend(myExplorer.config, settings);

Instead, create a new object that's the result of the merge leaving the first object (the defaults) untouched, like this:

this.settings = $.extend({}, myExplorer.config, settings);

What this does is still merge the passed objects into the first, but the first is a new object ({}), so we're not affecting either of the others, then just use this.settings (or a different name to make it absolutely clear) inside your object.

杀お生予夺 2024-10-04 01:42:18

根据我的理解,您正在尝试创建一个使用对象文字表示法定义的新对象实例。
对象文字可以使用 Object.create 方法实例化。
下面的代码解释了如何从对象文字表示法实例化对象。

            var objLiteral = {
                name:"kanthan",
                address:'',
                deliver:function(){
                    if(this.address){
                        console.log("Your product has been successfully delivered at "+this.address);
                    }
                    else{
                        console.log("please enter the address to deliver");
                    }
                }
            };
            var cum=Object.create(objLiteral);
            cum.address="gkm colony";
            objLiteral.deliver();
            cum.deliver();
            var cum1=objLiteral;
            cum1.address="gkm colony";
            objLiteral.deliver();
            cum1.deliver();

From my understanding you are trying to create a new instance of object which was defined using object literal notation.
object literals can be instantiated using Object.create method.
Here is the code that explains how to instantiate an object from object literal notation.

            var objLiteral = {
                name:"kanthan",
                address:'',
                deliver:function(){
                    if(this.address){
                        console.log("Your product has been successfully delivered at "+this.address);
                    }
                    else{
                        console.log("please enter the address to deliver");
                    }
                }
            };
            var cum=Object.create(objLiteral);
            cum.address="gkm colony";
            objLiteral.deliver();
            cum.deliver();
            var cum1=objLiteral;
            cum1.address="gkm colony";
            objLiteral.deliver();
            cum1.deliver();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文