0

var dataset = { num: 20 };
var svg = { w: 600 };
var column = {
    padding: 0.2,
    w: (svg.w/dataset.num)/(this.padding + 1),
    print: function(){
      console.log("through obj methord:" +
      (svg.w/dataset.num)/(this.padding + 1)
      );}
    };
column.print();
console.log(column);

    above is the code, and it could be executed, and in the result, you could see the result of column.w is NAN, while the same calculation in the obj's method: print could give back the right answer: 25.

    how could it be? even though i replaced (svg.w/dataset.num)/(this.padding + 1) by svg.w/(dataset.num*(this.padding + 1)) ,it is exactly the same.     after i replace the variables like svg.w, dataset.num with its values, column.w becomes value 25 of course.

1 Answers1

0

Try changing the this.padding to the value 0.25.

Javascript does not know what your this variable reffers to.

The “this” variable is a variable that each and every execution context gets, in a regular function call the “this” variable points at the global object or the window in the browser, which is the default. In a method call, which is a function within a variable, the “this” variable points at the method calling the object. The “this” variable is not assigned a value until the function where it is defined is actually called.

When you are using this in your code, it still points to the object which method you called. That object does not have a padding property, that's why your calculation can not be executed.

Read more about the this variable here

Adam Baranyai
  • 3,635
  • 3
  • 29
  • 68
  • you mean only in functions, *this* keyword will know which object it refers to? – Huang Qinlai Jan 11 '19 at 13:37
  • thank you, because this is a default global variable in the property, so it can't refer to the *column* object. and I also tried to replace *this* with *column*, and it says column is undefined without running over the column definition statement, so I think I should use the method when need *this* – Huang Qinlai Jan 11 '19 at 13:58