2

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();

3 Answers 3

5

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

calc_neighbours.call( this )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.