用过Vuejs
的同窗都知道,须要用new
操做符来实例化。前端
new Vue({ el: '#app', mounted(){}, });
那么面试官可能会问是否想过new
到底作了什么,怎么模拟实现呢。git
附上以前写文章写过的一段话:已经有不少模拟实现
new
操做符的文章,为何本身还要写一遍呢。学习就比如是座大山,人们沿着不一样的路爬山,分享着本身看到的风景。你不必定能看到别人看到的风景,体会到别人的心情。只有本身去爬山,才能看到不同的风景,体会才更加深入。
先看简单例子1:github
// 例子1 function Student(){ } var student = new Student(); console.log(student); // {} // student 是一个对象。 console.log(Object.prototype.toString.call(student)); // [object Object] // 咱们知道平时声明对象也能够用new Object(); 只是看起来更复杂 // 顺便提一下 `new Object`(不推荐)和Object()也是同样的效果 // 能够猜想内部作了一次判断,用new调用 /** if (!(this instanceof Object)) { * return new Object(); * } */ var obj = new Object(); console.log(obj) // {} console.log(Object.prototype.toString.call(student)); // [object Object] typeof Student === 'function' // true typeof Object === 'function' // true
从这里例子中,咱们能够看出:一个函数用new
操做符来调用后,生成了一个全新的对象。并且Student
和Object
都是函数,只不过Student
是咱们自定义的,Object
是JS
自己就内置的。
再来看下控制台输出图,感兴趣的读者能够在控制台试试。
与new Object()
生成的对象不一样的是new Student()
生成的对象中间还嵌套了一层__proto__
,它的constructor
是Student
这个函数。面试
// 也就是说: student.constructor === Student; Student.prototype.constructor === Student;
new
操做符作了两件事:[[Prototype]]
(也就是__proto__
)连接。接下来咱们再来看升级版的例子2:正则表达式
// 例子2 function Student(name){ console.log('赋值前-this', this); // {} this.name = name; console.log('赋值后-this', this); // {name: '轩辕Rowboat'} } var student = new Student('轩辕Rowboat'); console.log(student); // {name: '轩辕Rowboat'}
由此能够看出:这里Student
函数中的this
指向new Student()
生成的对象student
。segmentfault
new
操做符又作了一件事:this
。接下来继续看升级版例子3:数组
// 例子3 function Student(name){ this.name = name; // this.doSth(); } Student.prototype.doSth = function() { console.log(this.name); }; var student1 = new Student('轩辕'); var student2 = new Student('Rowboat'); console.log(student1, student1.doSth()); // {name: '轩辕'} '轩辕' console.log(student2, student2.doSth()); // {name: 'Rowboat'} 'Rowboat' student1.__proto__ === Student.prototype; // true student2.__proto__ === Student.prototype; // true // __proto__ 是浏览器实现的查看原型方案。 // 用ES5 则是: Object.getPrototypeOf(student1) === Student.prototype; // true Object.getPrototypeOf(student2) === Student.prototype; // true
关于JS的原型关系笔者以前看到这张图,以为很不错,分享给你们。浏览器
也就是这个对象会被执行[[Prototype]]
(也就是__proto__
)连接。而且经过new Student()
建立的每一个对象将最终被[[Prototype]]
连接到这个Student.protytype
对象上。app
细心的同窗可能会发现这三个例子中的函数都没有返回值。那么有返回值会是怎样的情形呢。
那么接下来请看例子4函数
// 例子4 function Student(name){ this.name = name; // Null(空) null // Undefined(未定义) undefined // Number(数字) 1 // String(字符串)'1' // Boolean(布尔) true // Symbol(符号)(第六版新增) symbol // Object(对象) {} // Function(函数) function(){} // Array(数组) [] // Date(日期) new Date() // RegExp(正则表达式)/a/ // Error (错误) new Error() // return /a/; } var student = new Student('轩辕Rowboat'); console.log(student); {name: '轩辕Rowboat'}
笔者测试这七种类型后MDN JavaScript类型,得出的结果是:前面六种基本类型都会正常返回{name: '轩辕Rowboat'}
,后面的Object
(包含Functoin
, Array
, Date
, RegExg
, Error
)都会直接返回这些值。
Object
(包含Functoin
, Array
, Date
, RegExg
, Error
),那么new
表达式中的函数调用会自动返回这个新的对象。结合这些小结,整理在一块儿就是:
[[Prototype]]
(也就是__proto__
)连接。this
。new
建立的每一个对象将最终被[[Prototype]]
连接到这个函数的prototype
对象上。Object
(包含Functoin
, Array
, Date
, RegExg
, Error
),那么new
表达式中的函数调用会自动返回这个新的对象。知道了这些现象,咱们就能够模拟实现new
操做符。直接贴出代码和注释
/** * 模拟实现 new 操做符 * @param {Function} ctor [构造函数] * @return {Object|Function|Regex|Date|Error} [返回结果] */ function newOperator(ctor){ if(typeof ctor !== 'function'){ throw 'newOperator function the first param must be a function'; } // ES6 new.target 是指向构造函数 newOperator.target = ctor; // 1.建立一个全新的对象, // 2.而且执行[[Prototype]]连接 // 4.经过`new`建立的每一个对象将最终被`[[Prototype]]`连接到这个函数的`prototype`对象上。 var newObj = Object.create(ctor.prototype); // ES5 arguments转成数组 固然也能够用ES6 [...arguments], Aarry.from(arguments); // 除去ctor构造函数的其他参数 var argsArr = [].slice.call(arguments, 1); // 3.生成的新对象会绑定到函数调用的`this`。 // 获取到ctor函数返回结果 var ctorReturnResult = ctor.apply(newObj, argsArr); // 小结4 中这些类型中合并起来只有Object和Function两种类型 typeof null 也是'object'因此要不等于null,排除null var isObject = typeof ctorReturnResult === 'object' && ctorReturnResult !== null; var isFunction = typeof ctorReturnResult === 'function'; if(isObject || isFunction){ return ctorReturnResult; } // 5.若是函数没有返回对象类型`Object`(包含`Functoin`, `Array`, `Date`, `RegExg`, `Error`),那么`new`表达式中的函数调用会自动返回这个新的对象。 return newObj; }
最后用模拟实现的newOperator
函数验证下以前的例子3:
// 例子3 多加一个参数 function Student(name, age){ this.name = name; this.age = age; // this.doSth(); // return Error(); } Student.prototype.doSth = function() { console.log(this.name); }; var student1 = newOperator(Student, '轩辕', 18); var student2 = newOperator(Student, 'Rowboat', 18); // var student1 = new Student('轩辕'); // var student2 = new Student('Rowboat'); console.log(student1, student1.doSth()); // {name: '轩辕'} '轩辕' console.log(student2, student2.doSth()); // {name: 'Rowboat'} 'Rowboat' student1.__proto__ === Student.prototype; // true student2.__proto__ === Student.prototype; // true // __proto__ 是浏览器实现的查看原型方案。 // 用ES5 则是: Object.getPrototypeOf(student1) === Student.prototype; // true Object.getPrototypeOf(student2) === Student.prototype; // true
能够看出,很符合new
操做符。读者发现有不妥或可改善之处,欢迎指出。
回顾这个模拟new
函数newOperator
实现,最大的功臣当属于Object.create()
这个ES5
提供的API
。
笔者以前整理的一篇文章中也有讲过,能够翻看JavaScript 对象全部API解析
Object.create(proto, [propertiesObject])
方法建立一个新对象,使用现有的对象来提供新建立的对象的__proto__。
它接收两个参数,不过第二个可选参数是属性描述符(不经常使用,默认是undefined
)。
var anotherObject = { name: '轩辕Rowboat' }; var myObject = Object.create(anotherObject, { age: { value:18, }, }); // 得到它的原型 Object.getPrototypeOf(anotherObject) === Object.prototype; // true 说明anotherObject的原型是Object.prototype Object.getPrototypeOf(myObject); // {name: "轩辕Rowboat"} // 说明myObject的原型是{name: "轩辕Rowboat"} myObject.hasOwnProperty('name'); // false; 说明name是原型上的。 myObject.hasOwnProperty('age'); // true 说明age是自身的 myObject.name; // '轩辕Rowboat' myObject.age; // 18;
对于不支持ES5
的浏览器,MDN
上提供了ployfill
方案。
if (typeof Object.create !== "function") { Object.create = function (proto, propertiesObject) { if (typeof proto !== 'object' && typeof proto !== 'function') { throw new TypeError('Object prototype may only be an Object: ' + proto); } else if (proto === null) { throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument."); } if (typeof propertiesObject != 'undefined') throw new Error("This browser's implementation of Object.create is a shim and doesn't support a second argument."); function F() {} F.prototype = proto; return new F(); }; }
到此,文章就基本写完了。感谢读者看到这里。
1.new
作了什么:
- 建立了一个全新的对象。
- 这个对象会被执行
[[Prototype]]
(也就是__proto__
)连接。- 生成的新对象会绑定到函数调用的
this
。- 经过
new
建立的每一个对象将最终被[[Prototype]]
连接到这个函数的prototype
对象上。- 若是函数没有返回对象类型
Object
(包含Functoin
,Array
,Date
,RegExg
,Error
),那么new
表达式中的函数调用会自动返回这个新的对象。
2.怎么模拟实现:
// 去除了注释 function newOperator(ctor){ if(typeof ctor !== 'function'){ throw 'newOperator function the first param must be a function'; } newOperator.target = ctor; var newObj = Object.create(ctor.prototype); var argsArr = [].slice.call(arguments, 1); var ctorReturnResult = ctor.apply(newObj, argsArr); var isObject = typeof ctorReturnResult === 'object' && ctorReturnResult !== null; var isFunction = typeof ctorReturnResult === 'function'; if(isObject || isFunction){ return ctorReturnResult; } return newObj; }
读者发现有不妥或可改善之处,欢迎指出。另外以为写得不错,能够点个赞,也是对笔者的一种支持。
做者:常以轩辕Rowboat若川为名混迹于江湖。前端路上 | PPT爱好者 | 所知甚少,惟善学。
我的博客segmentfault
前端视野专栏,开通了前端视野专栏,欢迎关注
掘金专栏,欢迎关注
知乎前端视野专栏,开通了前端视野专栏,欢迎关注
github,欢迎follow
~