js 手写篇-手写new 操作符

new 操作会经过下面几个过程

  • 1、创建一个新对象
  • 2、设置原型 将对象的原型(proto) 设置成构造函数的原型 (prototype)对象
  • 3、让函数的this 指向这个对象,执行构造函数中的代码 为这个对象添加新属性
  • 4、判断函数的返回值类型,如果是值类型 返回创建的对象。如果是引用类型,就返回这个引用类型的对象
function F(){name: 'gdy'};
let f = new F();
console.log(f.name) // 'gdy'

实现:

function objectFactory() {
  let newObject = null;  // 创建一个新对象
  let constructor = Array.prototype.shift.call(arguments);  // 是为了要取出传入的构造函数 Function F
  /**  constructor 为
    * function F(name){
        this.name = name;
        this.age = 18;
      }
   */
  let result = null;
  // 判断参数是否是一个函数
  if (typeof constructor !== "function") {
    console.error("type error");
    return;
  }
  // 新建一个空对象,对象的原型为构造函数的 prototype 对象
  newObject = Object.create(constructor.prototype);
  // console.log(newObject.__proto__ === constructor.prototype); //true

  // 将 this 指向新建对象,并执行函数
  // ↓ 之前 constructor 为 F{} this 指向之后为 F { name: 'gdy', age: 18 } ↓
  result = constructor.apply(newObject, arguments);  //argument 'gdy'
  // console.log(constructor.toString());
  // 判断返回对象
  let flag = result && (typeof result === "object" || typeof result === "function");
  // 判断返回结果
  return flag ? result : newObject;
}
// 使用方法
function F(name){
  this.name = name;
  this.age = 18;
}
let newf = objectFactory(F,'gdy');
console.log(newf.name); // 'gdy' 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值