Craig
Craig

Reputation: 2143

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','[email protected]','Johny'],
                    [2,'Bob','[email protected]','Bobby'],
                    [3,'Jenny','[email protected]','Jen'],
                    [4,'Mary','[email protected]','Maryann']
                ],
                test: this.data.length
            };

            var config = $.extend(defaults, settings);

            return this.each(function(){
                this.innerHTML = config.data.length;
                this.innerHTML += "<br />" + 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?

Upvotes: 2

Views: 111

Answers (3)

deceze
deceze

Reputation: 522081

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;

Upvotes: 0

Francois Deschenes
Francois Deschenes

Reputation: 24969

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/

Upvotes: 1

Chris Morgan
Chris Morgan

Reputation: 90752

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).

Upvotes: 1

Related Questions