对于下面的代码片段,我期望答案是“数字”,但我得到的是“未定义”。任何人都可以在这里帮助我找出它返回“未定义”的原因吗?
var foo = {
bar: function () {
return this.baz;
},
baz: 1
};
(function () {
return typeof arguments[0](); //this will return "undefined"
})(foo.bar);
如果我执行 typeof foo.bar(),那么它会给我预期的答案“数字”。
提前致谢。
最佳答案
那是因为普通函数的 this
是由调用函数的方式设置的,而不是定义函数的位置。 (ECMAScript2015 的“箭头”函数不同,它们从创建它们的地方继承 this
,而不是它们的调用方式。)
你有几个选择:
1) 使用 Function#bind
创建一个新函数,调用时将使用正确的 this
调用您的原始函数:
var foo = {
bar: function() {
return this.baz;
},
baz: 1
};
(function() {
snippet.log(typeof arguments[0]());
})(foo.bar.bind(foo));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
2) 使用你自己的封装函数:
var foo = {
bar: function() {
return this.baz;
},
baz: 1
};
(function() {
snippet.log(typeof arguments[0]());
})(function() {
return foo.bar.apply(foo, arguments);
});
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
关于javascript - 在方法中访问javascript对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32919725/