Playing with js -- the simulation implementation of new method

Keywords: REST

The role of new is known 1. The instance can access the properties and methods of the constructor 2. The instance can access the properties and methods in the constructor prototype

//demo:

function Person(name, age) {
  this.name = name
  this.age = age
}
Person.prototype.sayName = function () {
  console.log("this.name:",this.name)
}

const man = new Person("Zhang San",18)
console.log("demo man:", man) //Person {Name: 'Zhang San', age: 18}
man.sayName() //this.name: Zhang San

Preliminary realization


function myNew() {
    const result = new Object() //In the end, an object is returned, so first new one comes out

    const obj = Array.prototype.shift.call(arguments) //Use shift to intercept the first parameter, the constructor we need

    //In fact, this step can be avoided, because shift directly changes the original array, and then directly transfers arguments to apply
    const argArray = Array.prototype.slice.call(arguments)//Point this of the constructor obj to the result object, so that the result can access the properties or methods in obj

    result.__proto__ = obj.prototype // Second, inherit the attributes or methods on the prototype

    obj.apply(result, argArray) //First, point this of the constructor obj to the result object, so that the result can access the properties or methods in obj

    return result
}

const b = myNew(Person, "Zhang San",19)
console.log("test:", b) //Test: {Name: 'Zhang San', age: 19}

Perfect implementation, ha ha ha ha....

Step 2 Optimization

If the constructor returns a specified object, such as

function Person(name, age) {
  this.name = name
  this.age = age
  this.like = "rest"
  return {
    like:this.like
  }
}
const man = new Person("Zhang San", 18)
console.log("demo man:", man) //Demo man: {like: 'rest'}
console.log(man.name, man.age) //undefined undefined

code implementation

function myNew() {

  ,,,,
  ,,,,

  const  hasReturn = obj.apply(result,argArray)  //First, point this of the constructor obj to the result object, so that the result can access the properties or methods in obj
                                                 //At the same time, check whether the obj constructor returns, and whether the return is an object. Otherwise, return directly
  return typeof hasReturn === 'object' ? hasReturn : result
}


const b = myNew(Person, "Zhang San", 19)
console.log("test:", b) // Test: {like: 'rest'}
console.log(b.name, b.age) // undefined undefined

Complete, (^ - ^) V

tips: if the constructor does not return or does not return a specified object, such as return "hahaha", there is no difference between return and not return

Posted by zulubanshee on Tue, 24 Dec 2019 12:26:16 -0800