Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day7:写出执行结果,并解释原因 #43

Open
Genzhen opened this issue Jun 22, 2020 · 3 comments
Open

Day7:写出执行结果,并解释原因 #43

Genzhen opened this issue Jun 22, 2020 · 3 comments

Comments

@Genzhen
Copy link
Collaborator

Genzhen commented Jun 22, 2020

var fullname = 'a';
var obj = {
   fullname: 'b',
   prop: {
      fullname: 'c',
      getFullname: function() {
         return this.fullname;
      }
   }
};
 
console.log(obj.prop.getFullname()); // c
var test = obj.prop.getFullname;
console.log(test());  // a

每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案
欢迎大家在下方发表自己的优质见解
二维码加载失败可点击 小程序二维码

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。

@Genzhen
Copy link
Collaborator Author

Genzhen commented Jun 22, 2020

答案
c a

解析

  • 原因在于this指向的是函数的执行环境,this取决于其被谁调用了,而不是被谁定义了。
  • 对第一个console.log()语句而言,getFullName()是作为obj.prop对象的一个方法被调用的,因此此时的执行环境应该是这个对象。另一方面,但getFullName()被分配给test变量时,此时的执行环境变成全局对象(window),原因是test是在全局作用域中定义的。因此,此时的this指向的是全局作用域的fullname变量,即a。

@Genzhen Genzhen closed this as completed Jul 20, 2020
@yaooooooooo
Copy link

?????答不对题啊........

@Genzhen
Copy link
Collaborator Author

Genzhen commented Jul 22, 2020

?????答不对题啊........

@yaooooooooo 改过来了哈,感谢指正

@Genzhen Genzhen reopened this Jul 29, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants