初始问题
下面的代码应该返回1
,3
,因为x: 1
只是出现在return
语句之上--然而,它返回的是3
,1
。为什么会这样呢?当我们使用let
和/或const
时,结果是否相同?
如果你们能解释一下那就太好了,这样我就可以提高我的基本功了。下面是我的代码:
var x = 3;
var foo = {
x: 2,
baz: {
x: 1,
bar: function() {
console.log("this--->", this);
return this.x;
}
}
}
var go = foo.baz.bar;
alert(go());
alert(foo.baz.bar());
更新1:
在第一种情况下,bar
被认为是一个可以访问外部变量并输出3
的闭包
bar: function() { console.log("this--->", this); return this.x; }
发布于 2019-06-18 04:27:35
当您将foo.baz.bar
赋值给var
go
时,在赋值之后,go
只保存对内部函数的引用。如果它是从外部作用域调用的,则为x = 3
。实际上,函数中的this
取决于调用函数的作用域。
在第二种情况下,当您调用bar()
时,它位于从内部(即foo.baz
)调用的对象的作用域中,所以这一次函数bar()中的this引用了baz
、giving和so x = 1
。
关于javascript here中的作用域和this
的更多信息
发布于 2019-06-18 04:30:02
“this”关键字表示两个函数调用的两个不同对象。您可以通过在返回语句前添加'console.log(this);‘来查看它。尝试使用箭头函数来代替!
发布于 2019-06-18 04:33:01
在这里你可以在Function.prototype.bind
上阅读。这个方法应该能够帮助你解决你的问题。
检查下面的代码示例:
var x = 3;
const foo = {
x: 2,
baz: {
x: 1,
bar: function() {
return this.x;
}
}
}
//You're assigning a function definition to a variable, but this will not maintain scope:
const fn = foo.baz.bar;
//When called like this, bar() can be thought of as a method of foo.baz
console.log(foo.baz.bar()); //so we expect x = 1;
//You must properly bind your function reference to the desired "this" object:
const globalBound = fn; //which would be equivalent of: fn.bind(this);
const fooBound = fn.bind(foo);
const bazBound = fn.bind(foo.baz);
console.log(globalBound()); //x = 3
console.log(fooBound()); //x = 2
console.log(bazBound()); //x = 1
x = 'Now globalBound() will return a string';
foo.x = 'and so will fooBound(), but bazBound() will remain unchanged';
console.log(globalBound());
console.log(fooBound());
console.log(bazBound());
我鼓励您将var x = 3
更改为let x = 3
,并查看您的结果。
https://stackoverflow.com/questions/56638406
复制相似问题