Manually implement a new operation

Manually implement a new operation

Write in front


In all front-end interviews, I often like to test how the interviewer handwritten a new operator. As a third party preparing for the autumn recruitment, I also need to consider these. So let's take a look at what the new operator does, and what are the operations? Think through the following code:

// 
function Otaku(name, age) {
    this.name = name;
    this.age = age;
   // 
    this.habit = 'pk';
}
// 
Otaku.prototype.strength = 60;
Otaku.prototype.sayYourName = function () {
    console.log('I am ' + this.name);
}
// person 
const person = new Otaku(' ',5000);
person.sayYourName();
console.log(person);// 

Parsing

From the results printed on the console, we can see that the new operator probably did several things:

  1. Returned (generated) a new object
  2. Access to the properties in the constructor of the class Otaku
  3. Access to the properties and methods on the Otaku prototype and set the point of this (pointing to the newly generated instance object)

Through the above analysis and display, we can know that there must be Object in the new group, otherwise the creation of the object is a bit unclear. First come and write:

//   new  
//    +  
const person = new Otaku(' ',5000);
const person1 = objectFactory(Otaku, ' ', 5000);

// objectFactory   
function objectFactory(obj, name, age) {}
//   obj name   age   obj
// js   arguments  arguments 
function objectFactory() {
    console.log(arguements);//{ '0': [Function: Otaku], '1': ' ', '2': 5000 }
    // arguments objectfactory 
   // 
   // arguments :
   //1. Array.from(arguments).shift();//  shift 
   //2.[].shift().call(arguments);// call()  arguments shift 
    const Constructor = [].shift.call(arguments);
    const args = arguments;
   //   
    let obj = new Object();
   //   obj   
   // this 
   // Constructor obj this obj 
   // Coustructor this  call apply 
    Constructor.call(obj,...args);
    return obj;
}
 
  • The code above has too many comments, remove the code after the comment:
    function objectFactory() {
        let Constructor = [].shift.call(arguments);
        const obj = new Object();
        obj.__proto__ = Conctructor.prototype;
        Constructor.call(obj,...arguments);
        return obj;
    } 
  • There is another operation:
function myNew(Obj,...args){
  var obj = Object.create(Obj.prototype);//
  Obj.apply(obj,args);//  this  obj,   obj  
  return obj;// 
}