当前位置:网站首页>How the new operator works

How the new operator works

2022-06-24 03:33:00 HZFEStudio

Complete high frequency question bank warehouse address :https://github.com/hzfe/awesome-interview

Complete high frequency question bank reading address :https://febook.hzfe.org/

Related issues

  • new What does the operator do
  • new Simulation Implementation of operators

Answer key points

Constructors Object instances

new Operator by executing a custom constructor or a built-in object constructor , Generate the corresponding object instance .

In depth knowledge

1. new What does the operator do

  1. Create a new object in memory .
  2. The inside of the new object __proto__ Assigned to the constructor prototype attribute .
  3. Will be inside the constructor this Assigned as a new object ( namely this Point to a new object ).
  4. Execute the code inside the constructor ( Add properties to the new object ).
  5. If the constructor returns a non empty object , Returns the object . Otherwise return to this.

2. new Simulation Implementation of operators

function fakeNew() {
  //  Create new objects 
  var obj = Object.create(null);
  var Constructor = [].shift.call(arguments);
  //  Will be the object of  __proto__  Assigned to the constructor  prototype  attribute 
  obj.__proto__ = Constructor.prototype;
  //  Will be inside the constructor  this  Assign as new object 
  var ret = Constructor.apply(obj, arguments);
  //  Return to new object 
  return typeof ret === "object" && ret !== null ? ret : obj;
}

function Group(name, member) {
  this.name = name;
  this.member = member;
}

var group = fakeNew(Group, "hzfe", 17);

Reference material

  1. new The operator - MDN
  2. The new Operator
原网站

版权声明
本文为[HZFEStudio]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/09/20210926191930009r.html