构造函数中return的几种情况

能不能在构造函数中使用return呢?答案是可以的,但是return在使用过程中要知道一些规则

我们通过代码的形式,来了解了解

function TestA(name){
    this.name = name
    return 1 
}
function TestB(name){
    this.name = name
    return 'test'
}
function TestC(name){
    this.name = name
    return false
}
function TestD(name){
    this.name = name
    return [1,2,3]
}
function TestE(name){
    this.name = name
    return {}
}

我们在上面定义了5个构造函数,让他们分别返回不同的基本类型和引用类型的数据

下面我们来实例化这些构造函数,看看结果

let testA = new TestA('lili')
testA.  // TestA {name: 'lili'}
let testB = new TestB('lili')
testB. // TestA {name: 'lili'}
let testC = new TestC('lili')
testC // TestA {name: 'lili'}
let testD = new TestD('lili')
testD. //[1, 2, 3]
let testE = new TestE('lili')
testE. // {}

我们发现:

在构造函数中返回基本类型的数据,return不起作用;
在构造函数中返回引用类型的数据,实例化对象会返回return中的数据

这里请注意构造函数实例化对象要区别于函数的执行

let testA = TestA('lili')
testA  // 1
let testB = TestB('lili')
testB //'test'
let testC = TestC('lili')
testC //false
let testD = TestD('lili')
testD //[1, 2, 3]
let testE = TestE('lili')
testE // {}

是不是清楚了,利用new实例的对象和函数执行时return的情况不一样哈

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值