Skip to content

new #11

Description

@homobulla

使用new关键字调用函数的具体步骤:

  1. 创建空对象;
  var obj = {};
  1. 设置新对象的constructor属性为构造函数的名称,设置新对象的__proto__属性指向构造函数的prototype对象;
  obj.__proto__ = ClassA.prototype;
  1. 使用新对象调用函数,函数中的this被指向新实例对象:
  ClassA.call(obj);  //{}.构造函数();          
  1. 将初始化完毕的新对象地址,保存到等号左边的变量中

注意:若构造函数中返回this或返回值是基本类型(number、string、boolean、null、undefined)的值,则返回新实例对象;若返回值是引用类型的值,则实际返回值为这个引用类型。

可以看出,在new的过程中,主要实现了如下过程

  1. 声明一个中间对象
  2. 将该中间对象的proto指向构造函数的原型
  3. 将构造函数的this通过apply指向中间对象
  4. 返回该中间对象,也就是返回了实例对象

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions