微信小程序> es5、es6构造函数

es5、es6构造函数

浏览量:735 时间: 来源:prefectCC

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();//undefinedm.constructor===M.prototype.constructor;//truem.constructor===M;//true

es6构造函数

class F {  constructor() {console.log(2)    return this;  }}var f=new F();//2f.constructor===F;//truef.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;

版权声明

即速应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至197452366@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于即速应用观点。用户与作者的任何交易与本站无关,请知悉。

产品经理

手机 : 13312967497

擅长 : 小程序流量变现

扫码领取礼包

最新资讯

热门模板

  • 头条
  • 搜狐
  • 微博
  • 百家
  • 一点资讯
  • 知乎