🌟🌟🌟🌟🌟

Taste: Wangzai milk

Cooking time: 30min





Brendan Eich, a JavaScript author, once said that “it was a one-night stand between C and Self.”

Because it draws on the basic syntax of C language and the prototype-based inheritance mechanism of Self language.

So it’s also common to see JavaScript described as a prototype-based language, with one prototype-based object for every object.

An object uses its prototype as a template from which it can inherit properties and methods. A stereotype object is also an object and has its own stereotype object from which it inherits properties and methods.

Layer by layer, and so on…

If you are willing to open my heart layer by layer ~

The above relationship is

Prototype chainprototype chain

This paper tries to use easy to understand language (human language), to lead you to understand the prototype object, prototype chain.

Functions and objects

First, let’s look at the relationship between functions and objects in JavaScript, which will help us understand the prototype chain.

You might also see “everything is an object in JavaScript”, which is obviously wrong.

In fact, in JavaScript, there are many special object subtypes that can be called complex primitive types.

A function is a subtype of an object.

Functions are essentially objects.

But why do we get the following results when using Typeof for type checking?

var o = {};                 // Common objects
var f = function () {};     // Function object
console.log(typeof o);      //object
console.log(typeof f);      //function
Copy the code

JavaScript: Hey buddy, I’m the product of a one night stand, don’t ask for too much!

In JavaScript, detection of Object types, strongly recommend the use of the Object. The prototype. The toString method. Some of typeof’s return values are not defined in the standard documentation, so different engine implementations may differ.

To get back to the point, in fact, there is no essential difference between a function and an object; functions are special objects.

Function objects are born with a Prototype property, meaning that each function is born with a prototype object associated with it after it is created. This prototype object has a constructor property that points to the function.

Note:

Many people assume that newly created function objects have the constructor attribute in addition to the prototype attribute.

But it’s used hereconstructorProperties are actually retrieved from the stereotype chain

namelyFunction.prototype.constructor

Note: The ECMAScript standard’s section on function creation reads: NOTE A prototype property is automatically created for every function, to allow for the possibility that the function will be used as a constructor.

Explained that adding the Prototype attribute to a newly created function makes it easier to use the function as a constructor.

Now that we understand the relationship between functions and objects in JavaScript, let’s take a look at what a prototype object is.

A prototype object

When a constructor is created, it is associated by default with a new object of type Ojbect. This object is the prototype of the current constructor, which is an empty object by default.

Of course, objects created by the constructor have access to the properties and methods of the constructor prototype object.

// 1 declare the constructor Man
function Man(name) {
    this.name = name;
}

// 2 Print the Man prototype object to see
console.log(Man.prototype); // An empty Object of type Object

// 3 Add the getName method to the Man prototype object
Man.prototype.getName = function () {
    console.log(this.name);
}
// 4 Use the constructor to create an object instance
var d = new Man("Tibago.");
d.getName();  / / flute bugs
console.log(d);
Copy the code

By analyzing the above code and results, we can figure out the relationships among constructors, instances, and prototype objects.

We can draw the following conclusions

1. The constructor Man can access its prototype object through the prototype property.

2. D instantiated from Man can access Man’s prototype object via the __proto__ property.

3. The Man prototype object has access to its associated constructor via the constructor property.

We can access prototype objects in three ways

1. Constructor: prototype

2. Instance object __proto__

3. Object.getprototypeof (Instance object)

prototype

Prototype The property that the function object has that points to its prototype object.

proto

__proto__ All objects have a __proto__ attribute that points to the prototype of the instance.

constructor

Construtor constructors, a prototype object can be used to access the constructor to which it is associated. Of course, each instance object also inherits this property from the stereotype.

Note:

The __proto__ attribute is not in the ECMAScript standard, it is only for development and debugging, it is not universal and cannot appear in formal code.

Now that the prototype object is clear, let’s look at the prototype chain.

Prototype chain

function Man () {};
function Woman () {};

var m1 = new Man();
var w1 = new Woman();
Copy the code

That night, the prototype chain did a lot of things…

// 1. Let's look at the top of the food chain (prototype chain) null
console.log(Object.prototype.__proto__);                      //null

Prototype is object. prototype instead of itself
console.log(Function.prototype.__proto__ == Object.prototype);//true

// 3. The constructor for both Function and Object is Function
console.log(Function.constructor == Function);                //true
console.log(Object.constructor == Function);                  //true

// the prototype constructor is Function
console.log(Function.prototype.constructor == Function);      //true

// 5. M1 prototype object is man.prototype
console.log(m1.__proto__ == Man.prototype);  //true

/ / 6. Man. Prototyepe | Woman. The prototype of the constructor to Object
/ / Man. Prototyepe | Woman. The prototype of a prototype Object for the Object. The prototype
// Delete the instance member first and access it through the prototype member
delete  Man.prototype.constructor;
delete  Woman.prototype.constructor;
console.log(Man.prototype.constructor == Object);    //true
console.log(Woman.prototype.constructor == Object);    //true
console.log(Man.prototype.__proto__ == Object.prototype);    //true
console.log(Woman.prototype.__proto__ == Object.prototype);    //true

// the constructor for Man and Woman is Function
// The prototype objects of the Man and Woman constructors are empty functions
console.log(Man.constructor == Function);                //true
console.log(Woman.constructor == Function);                //true
console.log(Man.__proto__ == Function.prototype);        //true
console.log(Woman.__proto__ == Function.prototype);        //true
Copy the code

Access rules for the prototype chain

Nearby principle

When an object accesses a property or method, it checks its own instance and uses it if it exists. If it doesn’t exist, go to the prototype object to find it, and use it directly. If it doesn’t, go up the prototype chain to find it and use it. If it can’t find it, repeat the process until the top of the prototype chain.

Three test methods

The object.getProtoTypeof method is used to get the prototype Object of the specified instance Object.

function Demo(){};
var demo = new Demo();

console.log(Object.getPrototypeOf(demo));  // Prints the prototype object associated with the Demo
console.log(Object.getPrototypeOf(demo === Demo.prototype));  // true
console.log(Object.getPrototypeOf(demo === Demo.__proto__));  // true

Copy the code

The isPrototypeOf method is used to check whether an object is in the prototype chain of the specified object.

function Demo(){}
var demo = new Demo();

console.log(Demo.prototype.isPrototypeOf(demo)); // true
console.log(Object.prototype.isPrototypeOf(demo)); //true
Copy the code

The instanceof operator acts like the isPrototypeOf method, with the left operand being the instance object to be detected and the right operand being the constructor to be detected. Returns true if the right-hand operand specifies that the constructor’s prototype object is above the prototype chain of the left-hand operand instance object, false otherwise.

// 1 declare the constructor Demo
function Demo(){};
// 2 Obtain the instantiated object demo
var demo = new Demo();
// 3 Use isPrototypeOf
console.log(demo instanceof Demo);     //true
console.log(demo instanceof Object);   //true

// the prototype of the 4 Object constructor is in the prototype chain of the Function instance
console.log(Function instanceof Object); //true
// 5 The prototype Object of the Function constructor is in the prototype chain of the instance Object
console.log(Object instanceof Function); //true
Copy the code

Note: Don’t mistakenly think that instanceof checks whether the instance object was created from the current constructor instantiation. Instead, it checks whether the instance object inherits properties from the stereotype object of the currently specified constructor.

The best combination inheritance scheme

Train of thought

1. Use the prototype chain to achieve inheritance of prototype properties and methods

2. By forging (impersonating) constructor to realize the inheritance of instance members, and solve the problem of the parent constructor passing parameters

/ / 1 provides the supertype | parent types
function SuperClass(name) {
    this.name = name;
    this.showName = function () {
        console.log(this.name); }}// 2 Sets stereotype properties and stereotype methods for the parent type
SuperClass.prototype.info = 'SuperClass information ';
SuperClass.prototype.showInfo = function () {
    console.log(this.info);
};

// 3 Provides subtypes
function SubClass(name) {
    SuperClass.call(this,name);
}

// Get the instance member of the parent constructor person.call (this,name);
// Get the parent constructor's prototype member subclass.prototype = superclass.prototype;
SubClass.prototype = SuperClass.prototype;
SubClass.prototype.constructor = SubClass;

var sub_one = new SubClass("zhangsan");
var sub_two = new SubClass("lisi");
console.log(sub_one);
console.log(sub_two);
Copy the code

Refer to the top blog

communication

Welcome to my personal public communication, high-quality original articles will be pushed synchronously. Background reply welfare, you can receive welfare, you know ~

Your front canteen, remember to eat on time.