JS Notes: Object Oriented

1. Basic knowledge

JS does not distinguish between classes and instances, but implements object-oriented programming through prototypes.

The difference between JS's prototype chain and Java's classes is that all objects are instances. Inheritance just takes another object as a prototype.

// Prototype object 
let Player = {
    name: "Curry",
    number: 30
};

function createPlayer(name, number) {
     // Create a new object based on the prototype 
    let obj = Object.create(Player);
     // Initialize the new object 
    obj.name = name;
    obj.number = number;
    return obj;
}

let obj = createPlayer('Durant', 35);
alert(obj.name + ' #' + obj.number);
View Code

All objects have prototypes, and when we access an object's properties, JS will look backwards in the prototype chain.

Therefore, if the prototype chain is too long, the program will run slower.

 

2. Constructor

Constructors are actually just normal functions, but in JS you can use new to call the function and return an object.

function Player(name, number) {
    this.name = name;
    this.number = number;
    return this;
}

let obj = new Player('Durant', 35); // If there is no new, return undefined
View Code

 

Three, class

The object model of JS is based on prototype time, the advantage is simplicity, the disadvantage is that the implementation of inheritance requires writing a lot of code and correctly implementing the prototype chain. The new keyword class has been officially added to JS since ES6, and its purpose is to simplify the definition and inheritance of classes.

class Student {
    constructor(name, number) {
        this.name = name;
        this.number = number;
    }

    information() {
        return this.name + " #" + this.number;
    }
}

class CollegeStudent extends Student {
    constructor(name, number, school) {
        super(name, number);
        this.school = school;
    }

    information() {
        return super.information() + " " + this.school;
    }
}

let student = new CollegeStudent('Yao', '1200300456', 'GuiLin University of Electronic Technology');
alert(student.information());
View Code

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324870789&siteId=291194637