Traditional operas

Bengua has always believed that learning is not done overnight. It must require learners to repeatedly chew and hold knowledge points, constantly breaking and reshaping, in the long run, in order to achieve mastery and use for our own degree. The so-called: review old knowledge, not yiyi?

For JS skill owners, the concept of prototyping must be something to chew over in mind. This article and temporarily let this melon take you to see JS prototype 2 or 3, maybe there will be new harvest, why not?

✍ also need to encourage 💪 little hands a little 👍 good luck 🤞

The original meaning of the prototype

The prototype concept

JavaScript is often described as a prototype-based language — each object has a prototype object from which the object is a template and inherits methods and properties. (MDN)

Almost all objects in JavaScript are instances of Object at the top of the prototype chain, which is an interpretation of “Everything is an Object.”

Archetypes are products of our natural mind. As the saying goes, “imitate the gourd and gourd gourd” and “imitate the cat and the tiger”. The “gourd” here is the prototype of gourd gourd and the “cat” is the prototype of “tiger”. (PS: last weekend saw the movie “Dorit’s Adventures”, the tiger also likes to grab the spot of light, too funny, the prototype inherited the hammer!)

Prototype and class

Since everything is an object? Then you must have wondered: is JavaScript an object-oriented language? Why isn’t it like the concept of a class in Java?

JavaScript author Brendan Eich once said, “JavaScript is a one-night stand between C and Self.” (OS: Yes, a one-night stand. Who would have thought that creating a language with millions of learners would only take 10 days?)

His design idea went like this:

  1. Learn from the basic syntax of C language;
  2. Using the Java language for data types and memory management;
  3. Using Scheme language to elevate functions to the status of “first class”;
  4. Reference Self language, using prototype – based inheritance mechanism.

So JavaScript is not strictly object-oriented (it doesn’t encapsulate into a class), and the prototype-based inheritance mechanism is a feature of JS that goes deep into the soul.

  • Note: JavaScript classes introduced in ECMAScript 2015 (ES6) are essentially syntactic sugar for JavaScript’s existing prototype-based inheritance. Class syntax does not introduce a new object-oriented inheritance model to JavaScript.

Good TypeScript solution

Small AD: We are currently working on TypeScript. We have already published TypeScript, so please follow us and update later.

TypeScript is a superset of JavaScript that supports all object-oriented features such as classes, interfaces, and so on.

Here’s a small example:

// TypeScript

class Car { 

/ / field

    engine:string; 

 

// constructor

    constructor(engine:string) { 

        this.engine = engine 

    }  

 

/ / method

    disp():void { 

        console.log("Engine is:"+this.engine) 

    } 

}

Copy the code

// Compile to JavaScript

var Car = /** @class */ (function () {

// constructor

    function Car(engine) {

        this.engine = engine;

    }

/ / method

    Car.prototype.disp = function () {

        console.log("Engine is:" + this.engine);

    };

    return Car;

} ());

Copy the code

You can see that TypeScript classes are defined much like Java, but still converted to JavaScript to operate on the prototype chain.

Here’s a quick question: Is class-based always better than prototype-based? What are their respective strengths? Welcome to discuss ~

Call, apply, bind

Before we talk about prototype-based inheritance, we need to know these three. I’m sure you’re familiar with them. They’re very powerful.

The call, the apply

Call and apply are used to dynamically change this. When an object does not have a method, but some other function does, we can use call or apply to use the methods of other objects.

function Free() {

    this.free="free"

}



functionFood(name1,name2) {// Call receives separate arguments

    Free.call(this, name1,name2);

}

console.log(new Food('banana'.'apple').free);



functionFoods(ARR){// Apply accepts arrays

    Free.apply(this, arr);

}



console.log(new Food(['banana'.'apple']).free);

Copy the code

bind

Bind is similar to call, except that the bind method does not execute immediately (because it returns a function) and needs to be called again.

var food={name:"apple",func:function(val){console.log(this.name + val)}}



var banana=food.func.bind({name:'banana'},'good taste')



banana()

Copy the code

I’m going to make a hole here for the Function Coriolization to be filled in.

inheritance

Here we go! If you want to master the basic JS prototype, the following five inheritance methods, please be familiar with the heart. Use your hands, F12 up on the console?

Prototype chain inheritance

  • Prototype chain

Prototype chain? No bureaucratic explanations.

When looking for an Object property/method, if you don’t have the property/method, go to the constructor that created the Object. If you don’t find the property/method, go up until you reach Object.prototype.proto.

let obj = new Object()

obj.__proto__ === Object.prototype // true



Object.prototype.__proto__=null // Everything is empty

Copy the code
  • Prototype chain inheritance

Advantages: The ability to inherit the parent class’s prototype methods. (Example 1)

Disadvantages: All attributes on the stereotype are shared, so any subclass instance that modifies the attribute (reference type) in the stereotype will change the value of the attribute obtained by the other instance. (Example 2)

Example 1:

// Your parents have a house, you have a house

function Parent() {

    this.house='I own a house'

}

function Son() {

    

}



Son.prototype = new Parent()

Son. The prototype. The constructor = Son / / in order to more rigorous, change the default refers to the back

var son1=new Son()

Console. log(son1.house) // I have a room

Son.prototype.constructor

Copy the code

Oh, yeah. My Father the Warden series.

Example 2:

// If you have two sons and your parents have only one apartment, they want to paint the walls of different colors

function Parent() {

    this.houseColor=[]

}

function Son() {

    

}

Son.prototype = new Parent()

Son.prototype.constructor=Son



var son1=new Son()

son1.houseColor.push('Whitewash')



var son2=new Son()

son2.houseColor.push('Paint a red wall')



console.log(son1.houseColor) // ["Whitewash"."Paint the red wall."]

Copy the code

This is going to be a war! Old big just brush white wall, be second to brush red again…

Tectonic inheritance

Advantages: Solve the problem that the parent class attribute is a reference type shared by all instances and pass arguments to subclasses. (Example 3)

Disadvantages: Cannot inherit the stereotype method of supertype of superclass. (Example 4)

Example 3:

// Solve the problem of two sons painting the wall

function Parent() {

    this.houseColor=[]

}

function Son() {

Parent.call(this) // Change the this pointer

}

var son1 = new Son()

son1.houseColor.push('Whitewash')



var son2 = new Son()

son2.houseColor.push('Paint a red wall')



console.log(son1.houseColor) // ["Whitewash"]

Copy the code

Now the eldest son would not be angry, for the white walls he painted were still white.

Example 4:

// One wave is flat, another is rising. There is no inheritance of the prototype object.

function Parent() {

}

function Son() {

Parent.call(this) // Change the this pointer

}



Parent.prototype.getCar = function() {

    return 'I have a car'

}



var son1 = new Son()

son1.getCar() // getCar is not a function

Copy the code

Combination of inheritance

Combinatorial inheritance == prototype chain inheritance + construction inheritance

Advantages: Advantages of both

Disadvantages: Double execution of the parent constructor. (Example 5)

Example 5:

// Combination inheritance: I want them all. (OS: All, expensive…)

function Parent() {

    this.houseColor=[]

}

function Son() {

Parent.call(this) // Change the this pointer

}



Parent.prototype.getCar = function() {

    return 'I have a car'

}



Son.prototype = new Parent()

Son.prototype.constructor = Son



var son1 = new Son()

son1.houseColor.push('Whitewash')



var son2 = new Son()

son2.houseColor.push('Paint a red wall')



console.log(son1.houseColor,son1.getCar()) // ["Whitewash""I have a car."

console.log(son2.houseColor,son2.getCar()) // ["Paint the red wall.""I have a car."

Copy the code

So I painted the wall, and I got the car. The family is happy and harmonious, but the pressure of parents is a little too much.

Parasitic combinatorial inheritance

In order to solve the disadvantages of combinatorial inheritance, parasitic combinatorial inheritance is introduced.

Create (obj) creates a prototype by assigning an empty Object of obj to a subclass of the prototype.

Example 6:

function Parent() {

    this.houseColor=[]

}

function Son() {

Parent.call(this) // Change the this pointer

}



Parent.prototype.getCar = function() {

    return 'I have a car'

}



Son.prototype =  Object.create(Parent.prototype)

Son.prototype.constructor = Son



var son1 = new Son()

son1.houseColor.push('Whitewash')



var son2 = new Son()

son2.houseColor.push('Paint a red wall')



console.log(son1.houseColor,son1.getCar()) // ["Whitewash""I have a car."

console.log(son2.houseColor,son2.getCar()) // ["Paint the red wall.""I have a car."

Copy the code

ES6 inheritance

Inheritance is implemented through the class extends keyword. To be clear: classes in ES6 are syntactic sugar, and are essentially implemented by ES5 syntax.

Example 7:

class Parent{

    constructor() {

        this.houseColor = []

    }

    getCar() {

        return 'I have an old car.'

    }

}



class Son extends Parent{

    constructor(color){

        super()

        this.houseColor = color

    }

    getCar() {

        return "I have a new car."

    }

}

const son1 = new Son("Whitewash")

const son2 = new Son("Paint the red wall.")

console.log(son1.houseColor,son1.getCar()) // ["Whitewash""I have a car."

console.log(son2.houseColor,son2.getCar()) // ["Paint the red wall.""I have a car."

Copy the code

Publish and subscribe model

Why is the publish subscribe model highlighted here?

Because it also involves multiple situations.

  1. Multiple people subscribe to a publication.
  2. Multiple people subscribe to multiple publications.
  3. One person subscribes to a publication (Example 8).
  4. One person subscribes to multiple publications.

Each is worth writing about and playing with.

Example 8:

/*paper*/     

var paper={

    listen:' '.

    addlisten:function(fn){// Add subscribers

        this.listenList=fn;

    },

    trigger:function(){// Publish the message

        this.listenList.apply(this,arguments);

    }

}



/ * subscription * /

paper.addlisten(function(val){

    console.log("Xiao Wang subscribes news:"+val); 

}); 



/ * * /

paper.trigger("Newsweek is here.");



Copy the code

Here’s a hole dug for 24 design patterns to be filled.

summary

This article is a derivative of this melon shallow into deep TS process, these platitudes occasionally take a look, actually feel really good! The most important thing is that you can write on the console. When the old knowledge and the new knowledge collide, it is the time of harvest.

An inch into an inch of joy, that’s all.

I’m Carmelo Anthony of the Nuggets with you!

reference

  • The object prototype
  • Inheritance and prototype chains
  • Is JavaScript object oriented or object based? -winter
  • Javascript were born
  • How JavaScript implements inheritance