-1

I have a basic fundamental question. I execute the below code.

var app = {
  x: 10,

  start: function() {
    window.setTimeout(this.callback.bind(this), 10);
  },

  callback: function() {

    function print() {
      console.log('p '+ this.x);
    }

    console.log('c '+ this.x);
    print();

  }
};

app.start();

You can execute this code on jsbin

I expect it to output c 10 and p 10. Instead it outputs c 10 and p undefined. On further inspection, seems like this inside print() points to window object. Why would this be happening?

Goje87
  • 2,839
  • 7
  • 28
  • 48

3 Answers3

0

Because when you are calling print, you are not using any context, so this inside print refers to the window object.

You can pass a custom context to print by using .call() like

var app = {
  x: 10,

  start: function() {
    window.setTimeout(this.callback.bind(this), 10);
  },

  callback: function() {

    function print() {
      snippet.log('p ' + this.x);
    }

    snippet.log('c ' + this.x);
    print.call(this);

  }
};

app.start();
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

You are declared a global function inside the object. You can change to this:

callback: function() {

   this.print = function(){
      console.log('p '+ this.x);
   }

   this.print()

 }

Jsfiddle working: http://jsfiddle.net/rsf6gmr2/

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
-2

You need to use bind to print() function, to make it works.

function print() {
    console.log('p '+ this.x);
}.bind(this)

Because without it every function has own this object linked to window.

steppefox
  • 1,784
  • 2
  • 14
  • 19