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;//truees6构造函数
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:23、对象的 _ proto_一致
es5和es6的生成对象的proto 都是指向构造函数的prototype对象。修改一个对象的proto对象将会引起所有对象的更改
var f2=newF();f.__proto__===f2.__proto__ ;//true;















