面试官问:能否模拟实现`JS`的`new`操作符
me or you:木问题!!!
一、进行分析new的过程,主要有以下几点
1、创建一个新的对象
2、把obj的__proto__指向fn的prototype,实现继承
3、改变this的指向,执行构造函数、传递参数,fn.apply(obj,) 或者 fn.call()
4、返回新的对象obj
二、实现代码
<script>
/*
@author: guoguo
@title: 如何实现一个 new
@data:2019.2.19
*/
function Dog(name) {
this.name = name
this.say = function () {
console.log('name = ' + this.name)
}
}
function Cat(name) {
this.name = name
this.say = function () {
console.log('name = ' + this.name)
}
}
function _new(fn, ...arg) {
const obj = {}; //创建一个新的对象
obj.__proto__ = fn.prototype; //把obj的__proto__指向fn的prototype,实现继承
fn.apply(obj, arg) //改变this的指向
return Object.prototype.toString.call(obj) == '[object Object]'? obj : {} //返回新的对象obj
}
//测试1
var dog = _new(Dog,'aaa')
dog.say() //'name = aaa'
console.log(dog instanceof Dog) //true
console.log(dog instanceof Cat) //true
//测试2
var cat = _new(Cat, 'bbb');
cat.say() //'name = bbb'
console.log(cat instanceof Cat) //true
</script>
源码地址:https://github.com/GuoYuFu123/test-project/blob/master/new/new.html