js new关键字
实现new 关键字只需4步
1. 声明一个对象;
2. 把这个对象的__proto__ 指向构造函数的 prototype;
3. 以构造函数为上下文执行这个对象;
4. 返回这个对象。
简洁的代码示例如下:
function _new () {
var f = Array.prototype.shift.call(arguments);
var o = Object.create(f.prototype);
f.apply(o, arguments);
return o;
}
使用如下:
function Pers (name, age) {
this.name = name;
this.age = age;
this.speak = function () {
console.log(this.name);
}
}
var p2 = _new(Pers, 'xiaohua', 100);
console.log(p2);
p2.speak();

浙公网安备 33010602011771号