2

Can someone explaind what is happening here?

var dog = {
   name: "Dogo"
}

var echo = function() {
    console.log(this);
}

dog.echo = echo.bind(this);

echo();
dog.echo();

The first echo() prints out the global object as expected. However the second one prints empty object {} isntead of what the first echo() printed. Why?

Edit: Sorry! I didn't mention that the code is run by nodejs interpreter!

Thank you for help.

Paweł Smolak
  • 593
  • 6
  • 12
  • 7
    Can’t reproduce that. Are you running in Node? `this` isn’t the global object in module scope there, so when you call `echo.bind(this)` you’re binding a different object. – Ry- Dec 03 '17 at 11:26
  • Where is this code executed? – Felix Kling Dec 03 '17 at 11:27
  • 2
    In console both the thing are printing window object – simbathesailor Dec 03 '17 at 11:31
  • 1
    Possible duplicate of [In Javascript, why is the "this" operator inconsistent?](https://stackoverflow.com/questions/80084/in-javascript-why-is-the-this-operator-inconsistent) – moon Dec 03 '17 at 11:32
  • Sorry, this code is running inside nodejs interpreter, not the browser. I would never suppose there are any differences between these two. – Paweł Smolak Dec 03 '17 at 11:42

2 Answers2

3

Inside main scope of nodejs modules this variable refers to module.exports and by default it is equal to empty object {}, you can prove it this by running these tree line

console.log(this === module.exports);
module.exports.a = "a";
console.log(this);

and output should be

true
{ a: 'a' }

This is why you get empty object in second call


But inside a function in your module, this variable refers to global variable of nodejs, to prove it create a module like below and run it

global.bar = "baz";
function foo() {
    console.log(this === global);
    console.log(global.bar);
}
foo();

and output should be

true
baz

And this is why you get right object in your first call

Farnabaz
  • 4,030
  • 1
  • 22
  • 42
0

Bind function in javascript is to change the context to which "this" points to.

If you want to "this" in echo function to dog object that you have created, you should pass dog as the argument to bind.

dog.echo = echo.bind(dog);

Above line of code, change what "this" points in the echo function. So now it will point to the dog.

Here is the initial result of your code: enter image description here

In both cases "this" in echo pointed to global object.

Now here result once you provide dog as an argument to bind. As you can see "this" changed for the second console.log. It pointed to dog object. enter image description here

Javascript should behave in some way in the browser and on the server side (most of the time). Node is built on top of javascript. It uses the same v8 engine to compile the javascript code.