This series also does not have any tricks, is to complete the usual interview some handwriting functions, test these simple implementation of the advantage is that you can see the basic coding level, and take a short time, a more comprehensive view of your code strength. Generally, there are not many boundary conditions, so that the interview time is not enough, the investigation is not comprehensive.

If you don’t know or are not clear about the API, just ask the interviewer directly, how to use the API under Google anyone can immediately understand the knowledge also can’t see the level. The key is in the implementation process, and your coding status, habits, clarity of thought and so on.

Note that it is a simple implementation, not a complete implementation, it is important to clear the concept and clear implementation ideas, it is suggested to explain the concept first => write use cases => write pseudo-code => then realize specific functions, and then optimize, step by step.

8. instanceof

What is the

The instanceof operator is used to check whether the constructor’s prototype property appears on the prototype chain of an instance object.

Once this definition is out there, it’s a clear guide to the code, so it’s important to know what it is.

Several key

  1. In JavaScript, objects have a special hidden attribute [[Prototype]], which is either null or a reference to another object. The object is called a “stereotype,” which can also be interpreted as meaning that this property is a pointer to the stereotype object.

  2. Constructor F’s prototype property assigns the new object’s [[prototype]] value when new F is called.

For instance Rabbit, its constructor is Rabbit and its prototype is rabbit.prototype. Instanceof checks if the prototype exists on the chain of instances of rabbit, and returns true, not false

If you are not familiar with stereotypes, see the core Concepts article here to explain stereotypes and inheritance in JS

Simple handwriting implementation

implementation

  1. Write a few test cases first
console.log(myInstanceof([], Array)) // true
console.log(myInstanceof([], Object)) // true
// Note that the basic data type returns false directly
console.log(myInstanceof("aaa".String)) // false
Copy the code
  1. So let’s just write pseudocode first, get our heads together
function myInstanceof(left, right) {
    // Specifically, the basic data type returns false directly
    if(Base type) {return false
    }
    // Left is the checked party, and the first prototype Object to get it can be object.getProtoTypeof
    while(true) {layer by layer to the top of the prototype chain untilnullHalfway to find =>return trueIf no => {look up the prototype chainnullAll have no,false}}}Copy the code
  1. Implement master logic
function myInstanceof(left, right) {
  // The basic data type returns false
  if (typeofleft ! = ='object' || left === null) {
    return false
  }
  // getPrototypeOf is a method that comes with an Object Object and gets the prototypeof its parameters
  let proto = Object.getPrototypeOf(left)
  while (true) {
    // Not yet found
    if (proto === null) {
      return false
    } 
    // Find the same prototype object
    if(proto === right.prototype) {
      return true;
    }
    proto = Object.getPrototypeOf(proto)
  }
}

// console.log(myInstanceof([], Array))
Copy the code

9. New keyword

What is the

Analysis of the

New function implementation also needs to have a deep understanding of the prototype, it is recommended to read [core concepts] article to explain the prototype and inheritance in JS

And then we have to know what happens when new Foo() is executed, as MDN says, right

  1. One inherited fromFoo.prototypeA new object is created.
  2. useSpecified parametersCalling the constructorFooAnd willthis Bind to the newly created object. New Foo is equivalent tonew Foo(), that is, no parameter list is specified,FooCalled without any arguments.
  3. The object returned by the constructor is the result of the new expression. If the constructor does not explicitly return an object, the object created in Step 1 is used.

I actually recommend looking at the implementation steps below for clarity

Simple handwriting implementation

implementation

Write test cases first

// A student class constructor
function Student (name, age) {
    this.name = name;
    this.age = age;

    this.height = '180 cm';
}
// We hang a height attribute on the constructor prototype object
Student.prototype.weight = '60 kg';
// Hang the sayHello method. The advantage is that the method points to one place in memory, since it is prototyped
Student.prototype.sayHello = function () {
    console.log('hello ' + this.name);
}
Copy the code

Let’s look at the effects of the native new keyword

// Create the object boy1 using the Student constructor with the new keyword
var boy1 = new Student('Never'.'18');

// Constructor internal properties, including property methods on the stereotype chain, can be accessed by the instance
console.log(boy1.name, boy1.age) // Never 18
console.log(boy1.height) // '180 cm'
console.log(boy1.weight) // 60 kg

boy1.sayHello(); // hello Never
Copy the code

We need to achieve a similar effect

// This Constructor is passed in as the first argument, followed by the invocation of the argument to create the instance
let boy2 = myNew(Student, 'More'.'27')

// You need to implement constructor internal properties, including property methods on the prototype chain, which can be accessed by boy2 instances
console.log(boy2.name, boy2.age) // More 27
console.log(boy2.height) // 180 cm
console.log(boy2.weight) // 60 kg

boy2.sayHello() // hello More
Copy the code

Detailed step analysis

Below I have prepared a full description of myNew for you

function myNew() {
  // 1. Create an empty object
  let obj = {}

  // 2. Get the first argument to the constructor
  / / writing with Array. The prototype. The shift. The call (the arguments) in order to borrow Array. The shift on the prototype method
  // The shift method returns the first element from the front and removes it from the array to see if it prints after execution
  let Constructor = [].shift.call(arguments); 
  // console.log(Constructor) // [Function: Student] gets the first argument
  / / / / the console. The log (the arguments) {' 0 ':' More ', '1', '27'} the remaining parameters

  // 3. Point obj's [[Prototype]] to the constructor's Prototype, so that obj can access the properties in the constructor's Prototype
  // obj.__proto__ = Constructor. Prototype; way
  __proto__ is a historical getter/setter for [[Prototype]]
  Object.setPrototypeOf(obj, Constructor.prototype)

  // 4. Use apply to change the pointer of constructor this to the new object
  let res = Constructor.apply(obj, arguments);

  // 5. If the function does not return Object type, then the function call in the new expression automatically returns the new Object (obj).
  If the constructor returns an object, the object is returned directly
  return typeof res === "object" ? res : obj;
}

let boy2 = myNew(Student, 'More'.'27')
console.log(boy2.name, boy2.age) // More 27
console.log(boy2.weight) // '180 cm'
console.log(boy2.height) // '60 kg'

boy2.sayHello() // hello More
Copy the code

I think this comment already explains most of your questions, if you still don’t understand the comment section.

In addition, the development of language, grammar support after a lot of places can be simplified, the principle is the same, but with a new grammar

function myNew(Constructor, ... args) {
  Create an empty object and link it to the prototype object. Obj can access properties and methods in the constructor prototype
  // Use the Object. Create API to do the proto link
  let obj = Object.create(Constructor.prototype);
  Constructor. Prototype === null? Object.prototype : Constructor.prototype

  Obj can access properties in the constructor by binding this to implement inheritance
  let res = Constructor.apply(obj, args);

  If the constructor returns an object, it returns the object directly, otherwise it returns the new object obj
  return typeof res === "object" ? res : obj;
};

let boy2 = myNew(Student, 'More'.'27')
console.log(boy2.name, boy2.age) // More 27
console.log(boy2.weight) // '180 cm'
console.log(boy2.height) // '60 kg'

boy2.sayHello() // hello More
Copy the code

One of them is about Object.create, which I recommend to look at MDN for more information

In addition, we recommend another series of articles, very simple, on the front of the advanced students are very effective, wall crack recommended!! Core concepts and algorithms disassembly series remember to like ha

If you want to brush the questions with me, you can add me on wechat. Click here to make a friend Or search my wechat account, infinity_9368. You can chat with me and add my secret code “Tianwang Gaidihu”. Verify the message please send me Presious tower shock the rever Monster, I see it through, after adding I will do my best to help you, but pay attention to the way of asking questions, it is suggested to read this article: the wisdom of asking questions

reference

  • Developer.mozilla.org/zh-CN/docs/…
  • Developer.mozilla.org/zh-CN/docs/…
  • Developer.mozilla.org/zh-CN/docs/…