美文网首页js
new的过程都发生了什么

new的过程都发生了什么

作者: CRUD_科科 | 来源:发表于2019-06-24 13:42 被阅读0次
// 模拟new的方法
function mockNew() {
 let Constructor = [].shift.call(arguments);  // 取出类
 let obj = {};
 obj.__proto__ = Constructor.prototype;
 let r = Constructor.apply(obj, arguments);  //执行Animal并把this指向obj,所以obj.type === arguments中的type
 return obj instanceof Object ? r : obj;
}

function Animal(type) {
 this.type = type;
 return { 'a': '1' };   // 如果构造函数返回的是一个引用类型,就直接把对象返回 
}
Animal.prototype.say = function () {
 console.log('say')
}

let r = mockNew(Animal, 1);
// let r = new Animal(1);
console.log(r)
// console.log(r.type);
// r.say()

相关文章

网友评论

    本文标题:new的过程都发生了什么

    本文链接:https://www.haomeiwen.com/subject/ocgnqctx.html