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.
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
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:
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.