es5、es6构造函数

es5、es6构造函数区别

1 、生成对象的constructor函数区别。

  • 相同:es5和es6如果不定义constructor时,在新建new对象时都会默认生成。对象的constructor都指向构造函数也指向构造函数的prototype下的constructor函数(如下)
  • 不同:如果我们自己定义constructor,es5不会在新建对象时立即执行,但是es6时在new时自动执行constructor

es5构造函数

function M(){
    var a=1;
    this.constructor=function(){console.log(1)}
}
var m=new M();//undefined
m.constructor===M.prototype.constructor;//true
m.constructor===M;//true

es6构造函数

class F {
  constructor() {console.log(2)
    return this;
  }
}
var f=new F();//2
f.constructor===F;//true
f.constructor===F.prototype.constructor;//true;

2、调用方式

  • es5可以用new生成,对象,也可以直接调用构造函数,只是直接调用构造函数,将作为普通函数来用。例如可以调用函数M();
  • es6 必须用new生成对象。不能直接调用构造函数。
 F();//报错:VM845:1 Uncaught TypeError: Class constructor F cannot be invoked without 'new'  at <anonymous>:1:2

3、对象的 _ proto_一致

es5和es6的生成对象的proto 都是指向构造函数的prototype对象。修改一个对象的proto对象将会引起所有对象的更改

var f2=newF();
f.__proto__===f2.__proto__ ;//true;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值