Knowledge about

The new keyword in object oriented

Object Oriented Programming (OOP) is the mainstream Programming paradigm.

  • Create class instance – object
  • The constructor is executed when the instance is created
class Person {
    constructor(name) {
        console.log('constructor')
        this.name = name
    }
​
    say() {
        console.log('My name is ',this.name)
    }
}
const b = new Person("b");
Copy the code

Changes in the Javascript language

  • Changes in the way constructors are written
  • Define properties and methods through stereotypes
  • Introduction of the context this
function Person(name) {
  console.log("constructor");
  
  this.name = name;
}
Person.prototype.say = function () {
  console.log("My name is", this.name);
};
Copy the code

Function analysis of NEW

Function Person(name) {console.log("constructor"); function Person(name) {console.log("constructor"); // TODO: point the constructor's this to the new object this.name = name; } // TODO: Prototype person.prototype. say = function () {console.log("My name is", this.name); }; // TODO: create a new object const b = new Person("b"); b.say();Copy the code

Simulation function

function myNew(fn, ... Args) {// Create an empty object const obj = {}; // Link the __proto__ attribute of this object to the constructor prototype object obj.__proto__ = fn.prototype; Const res = fn.apply(obj, args); // Call the constructor as this context and receive the return value const res = fn.apply(obj, args); // If the return value exists and is a reference data type, the constructor returns the value, otherwise the created object is returned. Return Typeof res === "object"? res : obj; } const c = myNew(Person, "b"); c.say();Copy the code

The interview guide

  • How do face objects, stereotype chains, and apply bind contexts

review

  • Javascript is now all about the class keyword and functional reference transparency. But the legacy of contextual prototype chains is still needed