Can anyone explain why array.length would return two different results here?
Can you please look at this:
(function ($) {
$.fn.extend({
grid: function (settings) {
var defaults = {
data: [
['Code','Name','Email','Other'],
[1,'John','john@domain.com','Johny'],
[2,'Bob','bob@domain.com','Bobby'],
[3,'Jenny','jenny@domain.com','Jen'],
[4,'Mary','mary@domain.com','Maryann']
],
test: this.data.length
};
var config = $.extend(defaults, settings);
return this.each(function(){
this.innerHTML = config.data.length;
this.innerHTML += "<br /&开发者_运维技巧gt;" + config.test;
});
}
});
}(jQuery));
$('.content').grid();
http://jsfiddle.net/w8PG6/
And explain why the two results are different?
Also how do I achieve the desired result?
The problem is that when you call this.data.length
, it's actually counting the length of the jQuery data
function and not the length of defaults
. Additionally, you can't count the length of defaults.data
until after it's been assigned.
Have a look at this working example: http://jsfiddle.net/w8PG6/1/
Take a look at what this.data
is when you're doing this.data.length
. It's being evaluated based on the value of this
in the grid
anonymous function, which is jQuery.fn
. So it's jQuery.fn.data
. Function.length is the arity of the function (the number of arguments), which is 2 (key, value).
this
does not refer to your object under construction, but to whatever this
is in the current context. In your case this
just happens to have a property called data
. Compare with:
var foo = {
bar : "bar",
test : this.bar
}
This simply does not work. foo.test
is undefined
, unless there's a var bar
in the same context. I don't think it's possible to assign both values in the same statement, since the array won't be assigned to anything that can be accessed until the assignment statement is done. The best you can do is:
var defaults = { data : [ ... ] };
defaults.test = defaults.data.length;
精彩评论