记录下最近所学的知识,来检验自己的掌握程度;
**new**这个关键字的应用场景之一,便是用来实例化构造函数,
function Parent(name,age){
this.name = name;
this.age = age;
}
let obj = new Parent('401',18);
console.log(obj); // {name:401, age:18}
console.log(child.__proto__ === Parent.prototype)
构造函数Parent默认是没有返回值的,主要是因为两点:
-
构造函数返回引用类型的值(比如:function、array)会直接返回 -
构造函数返回基本类型的值才会默认返回一个实例化的对象同时我们可以看到,实例child的__proto__指向了 构造函数Parent的原型
我们来实现一个new:
function myNew(){
// 第一步 默认返回一个 空对象;
let obj = {};
// 第二步 获取构造函数
let Fn = Array.prototype.shift.call(arguments);
// 第三步 obj的__proto__ 指向 Fn
obj = Object.create(Fn.prototype); // 1
// 第四步 执行构造函数,获取构造函数的返回值,改变构造函数中的this指向
// 来指向创建的对象
let args = Array.prototype.slice.call(arguments)
let x = Fn.call(obj, ...args); // 2
// 第五步 返回值
// 如果x是引用类型就直接返回
if((typeof x == 'object' || typeof x == 'function') && x !== null){
return x
} else {
return obj;
}
}
let child2 = myNew(Parent,'王',18);
console.log(child2); // {name: "王", age: 18}
console.log(child2.__proto__ == Parent.prototype) // true
难免有错误,欢迎指出,谢谢。