簡體   English   中英

具有多個實例的javascript對象文字模式

[英]javascript object literal pattern with multiple instances

我開發了一個小的javscript小部件來將一些嵌套的<ul>塊轉換為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);

}

但這只是覆蓋第一個實例的配置值,這有效地打破了它。 我開始意識到對象文字模式不是去這里的方式,但我不確定是什么。 誰能提供任何指針?

在對象文字上使用函數,因此可以使用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({ .. });
...

那這個呢?

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

使用以下代碼來實現這一點,記住'公共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 

當您像這樣調用$.extend() ,它會將第二個對象的屬性合並到第一個:

$.extend(myExplorer.config, settings);

相反,創建一個對象,它是合並的結果,保持第一個對象(默認值)不變,如下所示:

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

這樣做仍然是將傳遞的對象合並到第一個,但第一個是新對象( {} ),所以我們不會影響其他任何一個,然后只使用this.settings (或者使用不同的名稱來制作它)絕對清楚)你的對象里面。

根據我的理解,您正在嘗試創建一個使用對象文字符號定義的對象的新實例。 可以使用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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM