首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >函数在两个单独的警报中返回不同的值

函数在两个单独的警报中返回不同的值
EN

Stack Overflow用户
提问于 2019-06-18 04:21:36
回答 3查看 59关注 0票数 0

初始问题

下面的代码应该返回13,因为x: 1只是出现在return语句之上--然而,它返回的是31。为什么会这样呢?当我们使用let和/或const时,结果是否相同?

如果你们能解释一下那就太好了,这样我就可以提高我的基本功了。下面是我的代码:

代码语言:javascript
复制
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; }

EN

回答 3

Stack Overflow用户

发布于 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的更多信息

票数 0
EN

Stack Overflow用户

发布于 2019-06-18 04:30:02

“this”关键字表示两个函数调用的两个不同对象。您可以通过在返回语句前添加'console.log(this);‘来查看它。尝试使用箭头函数来代替!

票数 0
EN

Stack Overflow用户

发布于 2019-06-18 04:33:01

在这里你可以在Function.prototype.bind上阅读。这个方法应该能够帮助你解决你的问题。

检查下面的代码示例:

代码语言:javascript
复制
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,并查看您的结果。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56638406

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档