繁体   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