1. 构造函数是什么,有什么作用
2. new命令的作用
3. 不使用new造成的影响与避免方法
function Fubar(foo, bar){ ‘use strict‘; this._foo = foo; this._bar = bar; } Fubar() // TypeError: Cannot set property ‘_foo‘ of undefined
2. 另一个解决办法,构造函数内部判断是否使用new命令,如果发现没有使用,则直接返回一个实例对象。
function Fubar(foo, bar) { if (!(this instanceof Fubar)) { return new Fubar(foo, bar); } this._foo = foo; this._bar = bar; } Fubar(1, 2)._foo // 1 (new Fubar(1, 2))._foo // 1
4. new命令的原理
5. new命令代码实现
function _new(/* 构造函数 */ constructor, /* 构造函数参数 */ params) { // 将 arguments 对象转为数组 var args = [].slice.call(arguments); // 取出构造函数 var constructor = args.shift(); // 创建一个空对象,继承构造函数的 prototype 属性 var context = Object.create(constructor.prototype); // 执行构造函数 var result = constructor.apply(context, args); // 如果返回结果是对象,就直接返回,否则返回 context 对象 return (typeof result === ‘object‘ && result != null) ? result : context; } // 实例 var actor = _new(Person, ‘张三‘, 28);
6. 判断函数调用时是否使用new命令
7. Object.create()创建实例对象
原文:https://www.cnblogs.com/wz-front-end/p/14957916.html