Samundra
Samundra

Reputation: 1909

how is this working in javascript constructor property

I have a code as follows:

function Cell(center) {
  this.center_cell = center;

  calc_neighbours = function() {
    var points = this.center_cell; 
    console.log(points); // displays undefined 
  };

  this.get_neighbours = function() {
    return calc_neighbours();
  };    
}

var c_points = new Array(8,2);
var cell = new Cell(c_points);
cell.get_neighbours();

With above code placed, the function cell.get_neighbours() displays undefined.

Now, If I make a slight change and have the following listed code, then function displays the values. Why is this happening is this because of function scope or variable scope inside javascript's object property.

Here is the code that displays the value:

function Cell(center) {
  this.center_cell = center;

  this.calc_neighbours = function() {
    var points = this.center_cell; 
    console.log(points); // displays undefined 
  };

  this.get_neighbours = function() {
    return this.calc_neighbours();
  };    
}

I haven't made any changes to the function usuage. i.e.

 var c_points = new Array(8,2);
 var cell = new Cell(c_points);
 cell.get_neighbours();

Upvotes: 2

Views: 62

Answers (3)

papercowboy
papercowboy

Reputation: 3459

To force context here or elsewhere, you can also use call:

calc_neighbours.call( this )

Upvotes: 0

v2b
v2b

Reputation: 1446

"this" is required so that the proper context is set. without the "this", everything binds to the global context (window), which isn't right in this case. And hence, it will not work without this. This is a little different from how Java and some other OO Languages are coded.

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382092

In

this.get_neighbours = function(){
    return calc_neighbours();
};  

you call calc_neighbours without providing a context. This makes the context the global one (window) in which points is undefined.

That's why you must call it as

this.calc_neighbours();

Upvotes: 5

Related Questions