是否可以在同一对象内引用对象? [英] Is it possible to reference object within the same object?
问题描述
我一直在纠缠jQuery插件代码,并且试图将所有公共变量放入单个对象中以便于访问.我在下面提供了一些有关如何执行此操作的示例,但我想知道其他人如何处理此问题.
I've been messing around with jQuery plugin code and I'm trying to put all of my common variables into a single object for easy access. I have included a few examples below on how I've done this, but I'm wondering how others deal with this problem.
让我说我有这个
var x = function(options){
var defaults = {
ulist : $('ul#list'),
listLen : $('ul#list').children().length
}
$.extend(options, defaults);
// do other stuff
}
我想做的是使用ulist
对象作为基础,然后找到li
的数量
What I'm trying to do is use the ulist
object in as a base, then find the number of li
's
我想我可以做到:
var x = function(options){
var defaults = {
ulist : $('ul#list'),
listLen : 0
}
defaults.listLen = defaults.ulist.children().length;
$.extend(options, defaults);
// do other stuff
}
或者这个:
var x = function(options){
var defaults = {
ulist : $('ul#list')
};
var defaults2 = {
listLen : defaults.ulist.children().length
}
$.extend(defaults, defaults2);
$.extend(options, defaults);
// do other stuff
}
以上代码示例只是一起使用,仅是为了使您理解该想法.无论如何,还有更好的方法吗?
The above code samples are just thrown together, and only meant to get the idea across to you. Anyway, is there a better way to do this?
推荐答案
我会说您发布的此版本,但无需将listLen
初始化为0
.
I would say this version that you posted, but no need to initialize listLen
to 0
.
var x = function(options){
var defaults = {
ulist : $('ul#list'),
listLen : 0 // Remove this line
}
defaults.listLen = defaults.ulist.children().length;
$.extend(options, defaults);
// do other stuff
}
您的第二个解决方案也可以使用,但是不需要对$.extend()
进行两次调用.它可以接受多个对象.
Your second solution would work too, but no need to do two calls to $.extend()
. It can accept more than one object.
$.extend(options, defaults, defaults2);
您的第一个解决方案似乎仍然更好.
Your first solution still seems better.
(如前所述,您可以使用一个函数.尽管我仍然在defaults
对象的初始化之外分配该函数,所以您可以在最后添加函数调用运算符()
并对其进行调用就像财产一样.
(As pointed to, you can use a function. Although I'd still assign the function outside the initialization of the defaults
object, so you can add the function call operator ()
at the end, and call it like a property.
var x = function(options){
var defaults = {
ulist: $('ul#list')
}
defaults.listLen = function() {return defaults.ulist.children().length}();
}
现在,您可以像访问属性一样访问defaults.listLen
并获取函数调用的结果,就像在jQuery对象上调用.length
一样.
Now you can access defaults.listLen
like a property and get the result of the function call, sort of like calling .length
on a jQuery object.
这篇关于是否可以在同一对象内引用对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!