js 的new关键字解析的过程中引擎执行了很多步骤,我们可以自己写一个仿new的函数来实现new关键字。
js new关键字的作用可以用下面的步骤大致列举一下:
- 创建一个空对象obj
- 将obj的 _proto_ 属性设置成构造函数的 prototype
- 将构造函数绑定这个变量执行
- 返回这个对象
function _new(constructor) {
//1 创建空的对象
//2 新对象的prototype指向构造函数
var obj = {
"__proto__": constructor.prototype // 必须用这种方式关联原型链
};
constructor.apply(obj,[].splice.call(arguments,1)); // 将构造函数绑定这个对象并执行
return obj; // 返回新对象
}
//构造函数
function MyClass(name,time) {
this.name = name || '';
this.time = time || '';
}
//生成一个实例
var my = _new(MyClass,'kruz_teching','2019');
console.log(my.name);
console.log(my.time);
console.log(typeof my);
console.log(my instanceof MyClass);
为什么要用new呢?
new可以实现继承链,new也可以共享原型链节省内存空间
如下一段代码
function Person(name){
this.name = name;
}
Person.prototype.sayName = function(){
console.log(this.name)
}
var p1 = new Person('zhangsan');
var p2 = new Person('lisi');
console.log(p1.sayName == Person.prototype.sayName); // true
console.log(p2.sayName == Person.prototype.sayName);// true
console.log(p1.sayName());
console.log(p2.sayName());
可以到p1 和 p2 的sayName函数和 Person.prototype.sayName相等的,实际上是一个函数,就算你new无数个Person对象,sayName函数还是同一份。
网友评论