Javascript OOP can't get property

I'm trying to rewrite my code to OOP approach, but stuck in something. There is an example :

   var counter = {
    column: {
    estimation: "tr td:nth-child(3)",
    worked:     "tr td:nth-child(4)",
    ratio:      "tr td:nth-child(5)",
    difference: "tr td:nth-child(6)"
    },

    columnLength : function display(){
        return $(this.column.estimation).length;
    },

Ok, it works! But if I will write almost the same, not in function though:

    var counter = {

    column: {
    estimation: "tr td:nth-child(3)",
    worked:     "tr td:nth-child(4)",
    ratio:      "tr td:nth-child(5)",
    difference: "tr td:nth-child(6)"
    },

    columnLength : $(this.column.estimation).length
    },

It doesn't, there is error : Column isn't declared.

Why it must be in function? Thx in advance.

Answers


The problem is that when you're using this inside the jQuery selector $(...) the value of it is the global object window instead of the object counter. So, basically, you're trying to call the property column of the object window window.column, that it doesn't exist.

If you run the following code, you'll see what's the value of this:

var counter = {

 column: {
  estimation: "tr td:nth-child(3)",
  worked: "tr td:nth-child(4)",
  ratio: "tr td:nth-child(5)",
  difference: "tr td:nth-child(6)"
 },

 columnLength: console.log(this)
} 

So, why is that happening?

Because when you're assigning an executed function to a parameter of a literal object, then that function is executed in the global context.

More info about the use of this: http://blog.kevinchisholm.com/javascript/context-object-literals/


Need Your Help

jquery keyup not fired until user clicks page first

jquery

I'm trying to setup some simple page navigation with keyups in jQuery. For instance, if the user presses the left arrow key, I want the page to load something.

how to center text of a JSpinner

java swing jspinner center-align

My question is self explanatory: how to center the text of a JSpinner? the methode setHorizontalAligment is not there. I also tried setAlignmentX, still nothing... Any help would be appreciated c: