gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:53:01 24 4
gpt4 key购买 nike

我开发了一个小的 javscript 小部件来转换一些嵌套的 <ul> block 进入 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({ .. });
...

关于具有多个实例的javascript对象文字模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3913103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com