【JavaScript】 当this遇上return

来源:互联网 发布:移动数据怎么改dns 编辑:程序博客网 时间:2024/05/20 12:22

参考地址

当this碰到return时,会出现一些小问题。

function fn()  {      this.user = '啊啊';      return {};  }var a = new fn;  console.log(a.user); //undefined
function fn()  {      this.user = '啊啊';      return function(){};}var a = new fn;  console.log(a.user); //undefined
function fn()  {      this.user = '啊啊';      return 1;}var a = new fn;  console.log(a.user); //啊啊
function fn()  {      this.user = '啊啊';      return undefined;}var a = new fn;  console.log(a.user); //啊啊

为什么呢?
如果返回值是一个对象,那么 this 指向的就是那个返回的对象,如果返回值不是一个对象那么 this 还是指向函数的实例。

null 虽然也是对象,但是在下面代码中,this指向的依旧是那个函数实例。因为null比较特殊。

function fn()  {      this.user = '追梦子';      return null;}var a = new fn;  console.log(a.user); //追梦子
0 0
原创粉丝点击