簡體   English   中英

javascript-根據屬性值獲取對象

[英]javascript - get Object based on property's value

...如果我具有以下構造函數,然后創建該類的實例:

    /* Gallery */
function Gallery( _horseName ){
    this.horseName = _horseName
    this.pixList = new Array();
}

var touchGallery = new Gallery( "touch" )

...如何根據horseName的值獲取Gallery對象?

考慮實現以下內容:

Gallery.prototype.getGalleryByHorseName = function( _horseName ){ /* to be implemented */}

...但是被卡住了。 有沒有更清潔或規范的方法來實現這一目標? 最終,我還必須在jQuery中訪問該Gallery對象。

提前致謝

最簡單的解決方案是將創建的對象保留在一個對象中。

var myGalleries = {};

myGalleries['touchA'] = new Gallery( "touchA" );
myGalleries['touchB'] = new Gallery( "touchB" );

然后,您可以通過傳遞密鑰快速訪問它們。

var galleryOfTouchB = myGalleries['touchB'];

你可以做這樣的事情。 我認為這很干凈而且規范:

var Galleries = (function() {
    var all = [],
        galleriesObj = {};

    galleriesObj.create = function(horseName) {
        var gallery = {
            horseName: horseName,
            pixList: []
        };
        all.push(gallery);
        return gallery;
    };

    galleriesObj.find = function(horseName) {
        var ii;
        for (ii = 0; ii < all.length; ii += 1) {
            if (all[ii].horseName === horseName) {
                return all[ii];
            }
        }
        return null;
    };

    return galleriesObj;
}());

var touchGallery = Galleries.create('touch');

var foundGallery = Galleries.find('touch');

您可以通過寫一個類來保存所有Gallery實例的列表,然后編寫一個遍歷每個Gallery對象並返回具有匹配名稱的對象的函數,從而以一種不錯的方式做到這一點。

Supaweu展示了一個非常簡單易用的示例(非oo)

您錯過了一兩個步驟。 您需要一個Gallery對象數組,然后在檢查_horseName屬性的同時迭代該數組。

您可以通過創建一個對象來填充該對象,該對象包含已經創建的馬名圖庫:

/* Gallery */
function Gallery( _horseName ){
    this.horseName = _horseName
    this.pixList = new Array();
    Gallery.galleryList[_horseName] = this; // Add this gallery to the list
}
Gallery.galleryList = {};

var touchGallery = new Gallery( "touch" )
var galleryByName = Gallery.galleryList["touch"];

暫無
暫無

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

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