A directory

What’s the difference between a free front end and a salted fish

directory
A directory
The preface
 2.1 Knowledge overview of this paper
 2.2 Why prototypes and prototype chains are needed
Common objects and function objects
Quad constructor
Five prototypes
Six constructor
Seven new
 7.1 write a new
 7.2 Question: Find the output
eightproto
Object and Function prototype pointing
 9.1 Review the previous content
 9.2 the Object and the Function
 9.3 Question: Expound the question
Ten prototype chain
 10.1 Everything is an object
 10.2 Topic 1: Finding the output
 10.3 Question 2: Finding the output
Eleven topics
 11.1 choice
 11.2 Explain the reasons
Xii References

The preface

Returns the directory

Above is the prototype chain god diagram, if you can understand, you need hardly read this article.

Remember to click on the “like” or “star” ~ this time must ah pro!

If you don’t understand, that’s ok. Here’s Jsliang nagging you slowly.

2.1 Knowledge overview of this paper

Returns the directory

  • The constructorfunciton Person() {}
  • The instanceconst person = new Person()
  • The prototypePerson.prototype
  • Hidden attributeconstructor
    • Equation 1:person.constructor === Person
    • Equation 2:Person.prototype.constructor === Person
  • new
    • newNative examples of
    • handwrittennewFirst, judge the first parameter as a function; Second, through theObject.create()Create new objects and bind prototype chains; Third, throughcallorapplycorrectionthisPointing and passing parameters; Fourth, throughtypeofDetermine function objects and ordinary objects; Function objects and ordinary objects return constructor valuesreturnValue, or return a new object
    • Write through your opponentnewWe’re going to do it with a sense of process
  • Find the prototype of the object corresponding to the instanceperson.__proto__ === Person.prototype
  • Function object pointing
    • person.__proto__ === Person.prototype
    • Person.__proto__ === Function.prototype
  • Plain object pointing
    • obj.__proto__ === Object.prototype
  • Prototype chain
    • foo.__proto__ === Object.prototype
    • F.__proto__ === Function.prototype
    • F.__proto__.__proto__ === Object.prototype

2.2 Why prototypes and prototype chains are needed

Returns the directory

Jsliang felt that the example he wrote in 2019 was clear:

Jsliang 2019 – Prototype and prototype chain

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.eat = function() {
    console.log(age + "Old" + name + "At dinner."); }}let p1 = new Person("jsliang".24);
let p2 = new Person("jsliang".24);

console.log(p1.eat === p2.eat); // false
Copy the code

As you can see, for each instance of the same function, we create a new heap, so that person 1 and Person 2 eat differently in the code above (return false).

It’s good to have things that are your own (your house, your car).

But it also has its downsides. After all, JavaScript only has so much space (memory), and you keep building houses, do you end up running out of space? (Out of memory)

Therefore, we need to think of a way to build objects similar to shared library (such as community public gym), so that when needed, everyone can go to the public gym to exercise, there is no need to open up new space.

How to open up this space, we need to use the prototype.

function Person(name) {
  this.name = name;
}

// Person defines a space called eat on its prototype that can be accessed by all members of the same cell
Person.prototype.eat = function() {
  console.log("Eat");
}

let p1 = new Person("jsliang".24);
let p2 = new Person("Liang Junrong".24);

console.log(p1.eat === p2.eat); // true
Copy the code

Look! So we have a public community gym.

I got it. Here we go! A lot of knowledge is ahead

Common objects and function objects

Returns the directory

In JavaScript, everything is an object. Do you want one? The new Object ()!

Of course, just like people, there is a distinction between ordinary people and geniuses.

Objects are also classified into ordinary objects and function objects.

Object and Function are JavaScript Function objects.

Let’s make a small distinction:

function fun1() {};
const fun2 = function() {};
const fun3 = new Function(a);const obj1 = {};
const obj2 = new Object(a);const obj3 = new fun1();

console.log(typeof Object); // function 
console.log(typeof Function); // function  

console.log(typeof fun1); // function 
console.log(typeof fun2); // function 
console.log(typeof fun3); // function   

console.log(typeof obj1); // object 
console.log(typeof obj2); // object 
console.log(typeof obj3); // object
Copy the code

In the above code, fun1, fun2, fun3 are function objects, and obj1, obj2, and obj3 are ordinary objects.

Keep this in mind and we’ll use it a lot

Quad constructor

Returns the directory

  • What is a constructor?

When any ordinary function is used to create a class object, it is called a constructor, or constructor.

It has several features:

  1. The default function starts with a capital letter
  2. throughnewCall a function
  3. The constructor returns an object

Such as:

function Person(name) {
  this.name = name;
}
const person = new Person('jsliang');
Copy the code

Here Person is the constructor, and Person is the instance object of the constructor Person (hereinafter referred to as the instance).

To see what constructors are, we should take a look at the implementation mechanism of new, but we will cover this later in the chapter.

Summary:

  • The constructorfunciton Person() {}
  • The instanceconst person = new Person()

Five prototypes

Returns the directory

In JavaScript, whenever an object is defined, it contains predefined properties.

Each of these function objects has a Prototype property that points to the prototype object called the function object (prototype for short).

function Person() {};
Person.prototype.name = 'jsliang';
Person.prototype.sayName = function() {
  console.log(this.name);
};

const person1 = new Person();
person1.sayName(); // jsliang

const person2 = new Person();
person2.sayName(); // jsliang

// The corresponding prototype method sayName is the same for both instances
console.log(person1.sayName === person2.sayName); // true
Copy the code

Prototype defines a public gym for the community (instance person1 and instance person2) in the prototype constructor.

Summary:

  • The prototypePerson.prototype

Six constructor

Returns the directory

Having said prototypes, let’s see what constructor means:

function Person(name) {
  this.name = name;
}
const person = new Person('jsliang');
Copy the code

In the code above, you have the constructor Person and its instance Person.

In JavaScript, each instance has a hidden attribute constructor.

Constructors and instances have an equation:

person.constructor === Person; // true
Copy the code

So one conclusion:

  • Instance propertiesconstructorPointing constructor

Also, the constructor of the function’s prototype points to the function:

Person.prototype.constructor === Person; // true
Copy the code

… class = ‘class =’ class = ‘class =’ class = ‘class =’ class = ‘class =’ class = ‘class =’ ‘

Summary:

  • Hidden attributeconstructor
    • Equation 1:person.constructor === Person
    • Equation 2:Person.prototype.constructor === Person

Seven new

Returns the directory

So we’ve got four things;

  • The constructorfunciton Person() {}
  • The instanceconst person = new Person()
  • The prototypePerson.prototype
  • Hidden attributeconstructor
    • Equation 1:person.constructor === Person
    • Equation 2:Person.prototype.constructor === Person

So, what does new do here? Let’s first look at a return case of native new:

function Person( name, age){
  this.name = name;
  this.age = age;
 
  // return; / / return this
  // return null; / / return this
  // return this; / / return this
  // return false; / / return this
  // return 'hello world'; / / return this
  // return 2; / / return this
  
  // return []; // Return the new [], person.name = undefined
  // return function(){}; // Return the new function, discard this, person.name = undefined
  // return new Boolean(false);           // 返回 新建的 boolean,抛弃 this, person.name = undefined
  // return new String('hello world'); // Return the new string, discarding this, person.name = undefined
  // return new Number(32); // Return the new number, discard this, person.name = undefined
}
var person = new Person("jsliang".25);
console.log(person); // Person {name: "jsliang", age: 25}
Copy the code

So, based on the return, let’s try writing new!

7.1 write a new

Returns the directory

Take a quick look at the final version:

function myNew(func, ... args) {
  if (typeoffunc ! = ='function') {
    throw 'The first argument must be the method body';
  }

  const obj = {};
  obj.__proto__ = Object.create(func.prototype);

  let result = func.apply(obj, args);

  const isObject = typeof result === 'object' && typeofresult ! = =null;
  const isFunction = typeof result === 'function';

  return isObject || isFunction ? result : obj;
}
Copy the code

The logic of it is:

  1. The first argument must be a function.const person = new Person()But we can’t get the real thingconst person = myNew(Person).
  2. Prototype chain inheritance. Let’s create a new objectobjtheobj__proto__Point to thefuncThe prototype of theprototype, i.e.,obj.__proto__ === func.prototype.
  3. correctionthisPoint to the. throughapplyThe bindingobjfunc, and pass the parameters as an array (the method body definition has already deconstructed the remaining parameters into arrays)
  4. Determines whether the constructor returnsObjectorFunction.typeofjudgeobjectNeed to rule outnullBecause thetypeof null === object.
  5. Non-functions and objects return the newly created object, otherwise return the constructor’s return value.

Finally, post a fully annotated version:

function myNew(func, ... args) {
  // 1
  if (typeoffunc ! = ='function') {
    throw 'The first argument must be the method body';
  }

  // 2. Create new objects
  const obj = {};

  // 3. The __proto__ of this object points to the protoobject of the func class
  // That is, the instance can access properties on the constructor. Prototype chain
  obj.__proto__ = Object.create(func.prototype);
  // Step 2 and Step 3 can be merged for compatibility with IE
  // const obj = Object.create(func.prototype);

  // 4. Bind this to apply and get the result
  let result = func.apply(obj, args);
  
  // 5. If the constructor returns a reference data type, return the result of the run
  // Otherwise return the newly created obj
  const isObject = typeof result === 'object' && typeofresult ! = =null;
  const isFunction = typeof result === 'function';

  return isObject || isFunction ? result : obj;
}

/ / test
function Person(name) {
  this.name = name;
  return function() { // Test point 5
    console.log('Return reference data type');
  };
}
// Test points 2 and 3
Person.prototype.sayName = function() {
  console.log(`My name is The ${this.name}`);
}
const me = myNew(Person, 'jsliang'); // Test point 4
me.sayName(); // My name is jsliang
console.log(me); // Person {name: 'jsliang'}

// Test point 1
// const you = myNew({ name: 'jsliang' }, 'jsliang'); // Error: the first argument must be the method body
Copy the code

7.2 Question: Find the output

Returns the directory

If you know how to write a new by hand, the following questions are easy:

var A = function() {};
A.prototype.n = 1;

var b = new A();
A.prototype = {
  n: 2.m: 3};var c = new A();

console.log(b.n); // Output what?
console.log(b.m); // Output what?

console.log(c.n); // Output what?
console.log(c.m); // Output what?
Copy the code

What is the output?


The answer:

b.n -> 1
b.m -> undefined

c.n -> 2
c.m -> 3
Copy the code

Analysis:

  1. b.nb.mExamination isnewAn implementation mechanism for. We know that in this scenarionewThe operation generates a new object to mount, so invar b = new A()The time,AThe prototype (prototype), and the mounted parameters are passed. namelyb.n1And theb.mundefined.
  2. With 1.c = new A()Is in theA.prototypeChanged the definition, so at this pointAThe data from the prototype was mounted.

Summary:

  • new
    • newNative examples of
    • handwrittennew
    • Write through your opponentnewWe’re going to do it with a sense of process

eightproto

Returns the directory

In the previous section, we mentioned that Person has its own public interval: Person.prototype.

So, if the residents of the community want to go to the public gym, how can they get there? (Person how to find Person.prototype)

In JavaScript, every JavaScript object (normal and function) has a __proto__ attribute that points to the object’s prototype.

Look at the code:

function Person() {};
const person = new Person();

console.log(person.__proto__ === Person.prototype); // true
Copy the code

So, now the residents of our community (example objects) know how to find the public gym (prototype)!

Summary:

  • Find the prototype of the object corresponding to the instanceperson.__proto__ === Person.prototype

Object and Function prototype pointing

Returns the directory

9.1 Review the previous content

Returns the directory

Now that we’ve covered the basics, it’s time to review and expand:

function fun1() {};
const fun2 = function() {};
const fun3 = new Function(a);const obj1 = {};
const obj2 = new Object(a);const obj3 = new fun1();

console.log(typeof Object); // function 
console.log(typeof Function); // function  

console.log(typeof fun1); // function 
console.log(typeof fun2); // function 
console.log(typeof fun3); // function   

console.log(typeof obj1); // object 
console.log(typeof obj2); // object 
console.log(typeof obj3); // object
Copy the code

Jsliang: In this code, which are function objects and which are ordinary objects, do you remember?

Yes, fun starts with Function objects: fun1, fun2, fun3, except for Object and Function.

Object and Function now!

9.2 the Object and the Function

Returns the directory

function Person() {};
const person = new Person();
Copy the code

In the code above, we see that the instance person is derived from the new constructor person.

So, where does “Person” come from?

Three ways to define a function object

const Person = new Function(a);Function Person() {};
Const Person = function() {};
console.log(Person.__proto__ === Function.prototype); // true
Copy the code

So put these two together:

const Person = new Function(a);const person = new Person();

console.log(person.__proto__ === Person.prototype); // true
console.log(Person.__proto__ === Function.prototype); // true
Copy the code

Oh oh, is there a feeling of sudden enlightenment?

Jsliang: person.prototype. __proto__ The next chapter is revealed

Now, what about objects?

const obj = new Object(a);// obj = {};
console.log(obj.__proto__ === Object.prototype); // true
Copy the code

Now that we understand a reference case for ordinary objects and Function objects and JavaScript’s built-in Object and Function objects, let’s do a quick problem.

9.3 Question: Expound the question

Returns the directory

function Person(name) {
  this.name = name;
}

let p = new Person('jsliang');
Copy the code

Question 1: What is p.__proto__ equal to?

Question 2: What is person.__proto__ equal to?


A:

  • p.__proto__ === Person.prototype
  • Person.__proto__ === Function.prototype

None. The content of this chapter has been explained, there is no need to elaborate here.

Summary:

  • Function object pointing
    • person.__proto__ === Person.prototype
    • Person.__proto__ === Function.prototype
  • Plain object pointing
    • obj.__proto__ === Object.prototype

Ten prototype chain

Returns the directory

In the above, jsliang asks person.prototype. __proto__ what is the corresponding?

Read this chapter to find out!

10.1 Everything is an object

Returns the directory

We need to start with the saying “everything is an object” :

function Person() {};
const person = new Person();

console.log(person.__proto__ === Person.prototype); // true
console.log(Person.__proto__ === Function.prototype); // true

console.log(person.__proto__.__proto__ === Object.prototype); // true
Copy the code

Let’s start with a knowledge point:

  • through__proto__And what I finally found wasnull

Well, isn’t everything an object?

Is!!! But where did the object come from, out of thin air:

  • Object.prototype.__proto__ === null

Object prototype __proto__ finds its final home: null.

This is like the neighborhood where the public gym, through the vacant lot, vacant = null.

This is just jsliang’s point of view, different people have different points of view, even from C++, etc

Person.__proto__.__proto__ === Object.

Let’s look at examples:

function Person() {};
Person.prototype.name = 'jsliang2';
Object.prototype.name = 'jsliang3';

const person = new Person();

// Current display
console.log(person.name); // jsliang2

// Add attributes to the instance
person.name = 'jsliang1';
console.log(person.name); // jsliang1

// Delete instance attributes
delete person.name;
console.log(person.name); // jsliang2 [Person. Prototype]

// Delete the constructor prototype
delete Person.prototype.name;
console.log(person.name); // jsliang3 [Object. Prototype]

// Delete the Object prototype
delete Object.prototype.name;
console.log(person.name); // undefined ();

console.log(person.__proto__ === Person.prototype); // true
console.log(person.__proto__.__proto__ === Object.prototype); // true
Copy the code

Stereotype chain: If an instance object does not have a property, JavaScript looks for the stereotype of that constructor. If the constructor’s prototype is not found, it continues to look for Object’s prototype. If Object does not already have a prototype, return undefined.

The chain:

  • Constructor. Prototype. XXX -> object.prototype.xxx

Is this clear:

  • person.__proto__ === Person.prototype
  • Person.__proto__ === Function.prototype
  • person.__proto__.__proto__ === Object.prototype
  • Object.prototype.__proto__ === null

So if there is code:

let str1 = 'jsliang1';
let str2 = new String('jsliang2');
Copy the code

What do these guys correspond to?

str1.__proto__ === ?
str1.__proto__.__proto__ === ?
str2.__proto__ === ?
str2.__proto__.__proto__ === ?
Copy the code

The answer:

  • str1.__proto__str2.__proto__Will be equal toString.prototype
  • str1.__proto__.__proto__str2.__proto__.__proto__Will be equal toObject.prototype

Finally, let’s take a look at other types of JavaScript prototype chains.

/ / string
let str = 'jsliang';
console.log(str.__proto__ === String.prototype);             // true
console.log(str.__proto__.__proto__ === Object.prototype);   // true

/ / digital
let num = 25;
console.log(num.__proto__ === Number.prototype);             // true
console.log(num.__proto__.__proto__ === Object.prototype);   // true

/ / a Boolean value
let bool = false;
console.log(bool.__proto__ === Boolean.prototype);            // true
console.log(bool.__proto__.__proto__ === Object.prototype);   // true

/ / array
let arr = [];
console.log(arr.__proto__ === Array.prototype);               // true
console.log(arr.__proto__.__proto__ === Object.prototype);    // true

/ / regular
let reg = /jsliang/g;
console.log(reg.__proto__ === RegExp.prototype);              // true
console.log(reg.__proto__.__proto__ === Object.prototype);    // true

/ / date
let date = new Date(a);console.log(date.__proto__ === Date.prototype);               // true
console.log(date.__proto__.__proto__ === Object.prototype);   // true
Copy the code

All things are objects

Let’s do a couple of quizzes.

10.2 Topic 1: Finding the output

Returns the directory

var F = function() {};

Object.prototype.a = function() {
  console.log('a');
};

Function.prototype.b = function() {
  console.log('b');
}

var f = new F();

f.a(); // Output what?
f.b(); // Output what?

F.a(); // Output what?
F.b(); // Output what?
Copy the code

What is the output?


The answer:

f.a() -> a
f.b() -> f.b is not a function

F.a() -> a
F.b() -> b
Copy the code

Resolution:

First, look at f:

var F = function() {};
var f = new F();
Copy the code

We know:

  • f.__proto__ === F.prototype
  • F.__proto__ === Function.prototype
  • f.__proto__.__proto__ === Object.prototype

Therefore, F.A () will first check whether F itself has a attribute; If not, look at F prototype F.prototype to see if there is a no; If not, look at Object.prototype and find a.

F.__proto__ is defined on function. prototype.

10.3 Question 2: Finding the output

Returns the directory

var foo = {};
var F = function() {};

Object.prototype.a = 'value a';
Function.prototype.b = 'value b';

console.log(foo.a); / / output
console.log(foo.b); / / output

console.log(F.a); / / output
console.log(F.b); / / output
Copy the code

What is the output?


A:

foo.a -> value a
foo.b -> undefined

F.a -> value a
F.b -> value b
Copy the code

Enumerative relations:

  • foo.__proto__ === Object.prototype
  • F.__proto__ === Function.prototype
  • F.__proto__.__proto__ === Object.prototype

So:

  1. fooWithout their ownaAttributes, then go toObjectGo up there and getvalue a. whilefoo.bI can’t find it. Go backundefined.
  2. FWithout their ownaAttributes, then go toFunctionWent up and looked, but did not find it; Move onObject.prototypeGo up, go backvalue a. whileFunction.prototypeThere arebProperty, returnsvalue b.

Eleven topics

Returns the directory

JavaScript prototype and prototype chain topic quite a lot, later gradually included here!

11.1 choice

Returns the directory

var F = function() {};

Object.prototype.a = function() {};
Function.prototype.b = function() {};

var f = new F();
Copy the code

Please select:

  • A:fCan take toaBut I can’t get itb.
  • B:fCan take toa,b.
  • C:FCan take tob, cannot geta.
  • D:FCan take toa, cannot getb.

Answer: A,

Resolution:

  • F.a = function
  • F.b = function
  • f.a = function
  • f.b = undefined

First of all, the function F can be found through the prototype chain

Object.prototype.a = function() {};
Function.prototype.b = function() {};
Copy the code

These two are bound to a and B.

But f = new f () comes out as an Object, not a Function.

So F can find A, but not B.

11.2 Explain the reasons

Returns the directory

Function.prototype.a = 'a';
Object.prototype.b = 'b';
function Person();
var p = new Person();

console.log(p.a); // undefined
console.log(p.b); // b
Copy the code

Please tell us why?


The answer:

The Person Function is an instance of the Function Object, so you can access the contents of the Function and Object prototype chains.

New Person returns an Object and can only access content mounted to the Object prototype chain.

So only P.B.

Xii References

Returns the directory

If you feel that after reading jsliang’s article, you still don’t understand the prototype and prototype chain.

Or if you want to understand more deeply and have your own set of ideas, you can see the following references:

  • Jsliang 2019 Interview – JavaScript- Prototype & Prototype Chain[Reading Suggestions: 1H]
  • 【 Why not three even 】 more simple than inherit the JS inheritance title – package (knife small test)[Reading Suggestions: 2H]
  • In-depth understanding of JavaScript prototypes[Reading Suggestions: 1H]
  • 【THE LAST TIME】 A thorough understanding of all JS prototype related knowledge points[Recommended Reading: 30min]
  • JavaScript goes from prototype to prototype chain[Recommended Reading: 30min]
  • JavaScript delves into the many ways to create objects, as well as the pros and cons【 Reading Suggestions: 10min】
  • JavaScript Engine basics: Prototyping optimization【 Reading Suggestions: 10min】
  • Detail JS prototype chain and inheritance[Recommended Reading: 30min]
  • In-depth understanding of JS objects and prototype chains from Proto and Prototype【 Reading Suggestions: 10min】
  • Code reuse pattern【 Reading Suggestions: 10min】
  • In-depth analysis of the various difficulties in the prototype【 Reading Suggestions: 10min】
  • The most detailed JS prototype and prototype chain ultimate detail, no “could be”. (a)[Reading Advice: Somewhat misleading]
  • The most detailed JS prototype and prototype chain ultimate detail, no “could be”. (2)[Reading advice: From the elevation book, do not continue to look back after the first]
  • The most detailed JS prototype and prototype chain ultimate detail, no “could be”. (3)[Reading advice: From the elevation book, do not continue to look back after the first]

Jsliang’s document library is licensed by Junrong Liang under the Creative Commons Attribution – Non-commercial – Share alike 4.0 International License. Based on the github.com/LiangJunron… On the creation of works. Outside of this license agreement authorized access can be from creativecommons.org/licenses/by… Obtained.