-1

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.

Victor Eliot
  • 87
  • 2
  • 7
  • Possible duplicate of [How does the "this" keyword in Javascript act within an object literal?](http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal) – James Thorpe Mar 17 '16 at 09:45

1 Answers1

0

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/

Jose
  • 28
  • 4