简体   繁体   English

绑定函数的怪异行为

[英]Weird behavior of bound function

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. 第一个echo()按预期打印出全局对象。 However the second one prints empty object {} isntead of what the first echo() printed. 但是,第二个打印的空对象{}与第一个echo()打印的内容不符。 Why? 为什么?

Edit: Sorry! 编辑:对不起! I didn't mention that the code is run by nodejs interpreter! 我没有提到代码是由nodejs解释器运行的!

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 在nodejs模块的主要范围内, this变量引用module.exports ,默认情况下它等于空对象{} ,您可以通过运行以下树行来证明这一点

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 但是在模块的函数内部, this变量引用nodejs的global变量 ,以证明它可以像下面那样创建一个模块并运行它

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. javascript中的绑定功能是更改“ this”所指向的上下文。

If you want to "this" in echo function to dog object that you have created, you should pass dog as the argument to bind. 如果要在echo函数中将“ this”设置为创建的dog对象,则应将dog作为绑定参数。

dog.echo = echo.bind(dog); dog.echo = echo.bind(dog);

Above line of code, change what "this" points in the echo function. 在代码行上方,更改echo函数中“ this”指向的内容。 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. 在这两种情况下,回显中的“ this”都指向全局对象。

Now here result once you provide dog as an argument to bind. 现在,一旦您提供dog作为要绑定的参数,这里就是结果。 As you can see "this" changed for the second console.log. 如您所见,第二个console.log的“ this”已更改。 It pointed to dog object. 它指向狗的对象。 在此处输入图片说明

Javascript should behave in some way in the browser and on the server side (most of the time). Javascript应该在浏览器和服务器端(大多数时间)以某种方式运行。 Node is built on top of javascript. Node建立在javascript之上。 It uses the same v8 engine to compile the javascript code. 它使用相同的v8引擎来编译javascript代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM