1
var Todo = function(x){
 this.data = x;
    this.view = function(){
        alert("hi")
        check()
    }
    check = function(){
        alert("checking")
        alert(this.data)
    }
}
Todo.prototype.add = function(item){
    this.data.push(item)
}
var todo = new Todo([1,2,3])
alert(todo.data)
todo.add(5)
alert(todo.data)
todo.view()

In above code why I am not able to get the value of data in check method. I am little confused.

jbmyid
  • 1,985
  • 19
  • 22
  • Maybe the following answer will be helpful to you: http://stackoverflow.com/a/16063711/1641941 As correctly answered the function check is a member of window (window.check) so when calling `window.check` then the invoking object is `window`. Invoking object is what `this` represent in the function body. – HMR Jan 06 '14 at 12:59

2 Answers2

3

this in the check function refers to the global object window.

Fix it with:

var Todo = function(x){
    this.data = x;
    this.view = function(){
        alert("hi");
        this.check();
    };
    this.check = function(){
        alert("checking");
        alert(this.data);
    };
};

And if you don't want to expose check method public, then you could do like below.

var Todo = function(x){
    this.data = x;
    this.view = function(){
        alert("hi")
        check.apply(this); //here, by using apply method
    }
    var check = function(){
        alert("checking")
        alert(this.data)
    }
}
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • yes that i know, i have tried that in jsfiddle, but I want to know why in check method this is not accessible? and if i check this in check method it gives me window object. – jbmyid Jan 06 '14 at 11:37
  • @jbmyid the value of `this` is determined by how a function is called. – xdazz Jan 06 '14 at 11:40
1

you have declared check as a global variable:

var a = 5; local variable
a = 5; global variable (attached to window)

therefore, the function context(this) is bound to Window when calling check(), which does not contain data property.

so you have to attach check function to Todo "class":

this.check = function() {};

a side note, you could get the desired functionality by setting manually the function context to todo when invoking the function:

check.apply(todo);
Amine Hajyoussef
  • 4,381
  • 3
  • 22
  • 26