Last time we talked about functions and the scope of functions that are often asked in front end interviews. In this post today we are going to talk about one of the more important issues of JS, even in the programming world, object orientation.

Is everything an object in JavaScript?

“Everything! Everybody believes that. In fact, there are a lot of language traps, it is better not to go around bragging to others that everything is the object.

The data type

JavaScript is a weakly typed or dynamic language. This means that you don’t have to declare the type of the variable in advance; the type will be determined automatically as the program runs. This also means that you can use the same variable to store different types of data. The latest ECMAScript standard defines seven types of data:

Basic types of

  • Boolean
  • Null
  • Undefined
  • Number
  • String
  • Symbol (new definition in ECMAScript 6)

Object type

  • Object

Object types cover many reference types, and anything that is not a basic type is an object type. Function, for example, is a generic object with a callable Function attached.

According to this classification, “not everything is connected”.

We can distinguish between the two types in two ways:

The difference between

variability

Basic type: immutable type, cannot add attributes; Even if an attribute is added, the parser cannot read it further;

var cat = "cat";
cat.color = "black";
cat.color // undefined
Copy the code

Object type: a mutable type that supports adding and removing properties.

Compare and pass

Basic types: compare by value, pass by value; Object type: Compare by reference, pass by reference.

// Basic type var cat ="tom";
var dog = "tom";
cat === dog // true// Object type var cat = {name:"tom"};
var dog = {name:"tom"};
cat === dog //false
Copy the code

We say object comparison by reference: whether two objects have the same value depends on whether they refer to the same underlying object __David Flanagan

So let’s change it to this:

var cat = {name:"tom"}
var dog = cat;
b.name = "Haba"

dog === cat // true
Copy the code

How do I detect object types? Or how do I detect if a data is an array type?

Detect the type of an Object, strongly recommended to use the Object. The prototype. The toString method; Because it’s the only way we can rely on it. We use the Object. The prototype. The toString method:

Object.prototype.toString.call([])    // "[object Array]"
Object.prototype.toString.call({})    // "[object Object]"
Object.prototype.toString.call(2)    // "[object Number]"
Copy the code

Why can’t you use typeOf?

Typeof only works on basic types. In reference types (except Function) it returns object, and typeof null === “object”.

A brief talk about object orientation

Object Oriented programming (OOP) is the mainstream programming paradigm at present. Its core idea is to abstract all kinds of complex relations in the real world into objects, and then complete the simulation of the real world through the division of labor and cooperation between objects.

An object is an abstraction of a single object, a book, a cat, a person. From a language perspective, an object is a container that encapsulates properties and methods.

There are two main concepts of typical object orientation: classes and instances

  • Class: The type template of an object
  • Instance: An object created from a class

JavaScript, unfortunately, has no concept of classes, but it uses constructors as templates for objects.

// Constructor var Pet =function (name, language) {
    this.name = name;
    this.say = function() { console.log(language); }} // The new keyword generates objects. We'll talk about the new operator later. var cat = new Pet('tom'.'meow');
cat.name // tom
cat.say() // meow
Copy the code

What does new do to create an object?

New is used to create a new object, for example:

function Pet () {}
var tom = new Pet();
Copy the code

New performs the following operations:

  • Create an empty object, reference it with the this variable and inherit the prototype of the function
  • Properties and methods are added to the reference object of this
  • The newly created object is referred to by this and implicitly returns this

    Simulation process:

    function newObj(Fun,arguments) {
        var o = {};
        if (Fun && typeof Fun === "function") {
            o.__proto__ = Fun.prototype;
            Fun.apply(o, arguments);
            returno; }}Copy the code

Note here that the constructor has a return statement inside it. If a return is followed by an object, the new command returns the object specified by return. Otherwise, return this regardless of the return statement.

var Pet = function (name) {
    this.name = name;
    return {notInstance:"blabla"}
}
var cat = new Pet('tom');
cat.name // undefined
cat.notInstance // blabla
Copy the code

Explain the prototype chain? How does JS implement inheritance?

The constructor mentioned above, the properties and methods of the instance object are implemented inside the constructor. Such constructors have a disadvantage:

var cat1 = new Pet('tom'.'meow');
var cat2 = new pet('jery'.'meow');

cat1.say === cat2.say // false
Copy the code

Generate the same two cats, but the cat’s say method is different, that is, each new object generates a new say method. All say methods have the same behavior and are fully shareable. The JavaScript prototype allows us to share.

Prototype chain?

JavaScrip can generate a new object using a constructor. Each constructor has a Prototype property, and each object generated through this constructor has an internal private proTO to the constructor’s prototype Otype, because it’s an object, has its own prototype, and so on and so forth until the prototype is null, and that’s the prototype chain.

How prototype chains work:

function getProperty(obj, prop) {
    if(obj. HasOwnProperty (prop)return obj[prop]
    else if(obj.__proto__ ! == null)returnGetProperty (obj.__proto__, prop) // How about not having a private property and looking up the prototype chain until it finds one, and returning undeFind if it doesn'telse
        return undefined
}
Copy the code

If you follow the prototype chain layer by layer, all objects can find the top layer, Object. Prototype, that is, the Object constructor’s Prototype property, and Object. Prototype Object points to the null Object without any properties and methods.

Object.getPrototypeOf(Object.prototype)
// null
Copy the code

Prototype chain indicates the process of an Object looking for its properties: first look at the Object itself -> not found and then look at the prototype of the Object -> not found and then look at the prototype -> until object. prototype is not found -> return undefined. (If found in this lookup, return immediately).

The constructor property

The Prototype object has a constructor property, which by default points to the constructor of the Prototype object. Because the constructor property is an association between a stereotype object and a constructor, be careful when modifying a stereotype object.

var Pet = function(name) { this.name = name; } // Avoid this as it overwrites the construct property. Pet.prototype = { say:function () {
        console.log('meow'); }} // Remember to point it back if we overwrite the constructor attribute. Pet.prototype.constructor = Pet;Copy the code

The difference between the __proto__ and prototype properties

Prototype is a property specific to the function object. __proto__ is an implicit attribute of a normal object. When new, it refers to the object that Prototype refers to. __proto__ is actually a property of an entity object, and prototype is a property of the constructor. __proto__ can only be used in learning or debugging environments.

Here are two points:

  • The constructor accesses the prototype object through the Prototype property
  • Instance objects access prototype objects via [[prototype]] internal attributes. The browser implements the __proto__ attribute for instance objects to access prototype objects

When Object is a constructor, it is an instance of Function. If Function is a constructor, then function. prototype is an Object instance.

Let’s look at a topic:

var F = function() {}; Object.prototype.a =function() {}; Function.prototype.b =function() {}; var f = new F(); // can f fetch a,b? How does it work?Copy the code

According to the relationship of prototype chain:

F is an instance object of F, whose prototype chain:

f.__proto__ -> [F prototype].__proto__ -> [Object prototype].__proto__ -> null
Copy the code

F is a constructor, an instance of Function, whose prototype chain:

F.__proto__ -> [Function prototype].__proto__ -> [Object prototype].__proto__ -> null
Copy the code

Function prototype = Function prototype = Function prototype = Function prototype = Function prototype = Function prototype = Function prototype

Prototype inheritance

Prototype inheritance is to create a new object with the help of the existing object. By pointing the prototype of the subclass to the parent class, it is equivalent to joining the prototype chain of the parent class.

function Animal(){
    this.super = 'animal';
}
function Cat(name) {
    this.name = name;
    this.food = 'fish'; } Cat.prototype = new Animal(); // Animal cat.prototype.getFood =function () {
    return this.food;
}
Copy the code

There is something wrong with the constructor direction in the above method:

var cat = new Cat('tom');
cat.name // tom
cat.super // animal
cat.getFood() // fish
//but
cat.constructor === Cat //false
cat.constructor === Animal //true
Copy the code

Cat’s constructor does not point to cat but to its parent Animal. We need to fix it:

function Cat(name){
    this.name = name;
    this.food = 'fish';
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
Cat.prototype.getFood = function () {
    return this.food;
}
Copy the code

There you have it: a simple prototype inheritance.

conclusion

In terms of object orientation, I would say that JS is “almost everything”, because of the existence of prototype chains we can implement inheritance similar to other languages.

Plus the previous one, the two articles have covered most of the INTERVIEW questions of JS, and the next article may explain a single thread model and timers. This one is a difficult one and IT took me a lot of data to figure it out. This interview series is mainly aimed at the “middle and senior front end”, but also an advanced level, you see the officer do not lose heart, everything will be a cloud one day.

The women’s volleyball team won the championship. It seems that many times I paid attention to this year had a perfect ending. I am very happy for them, and I hope my future will also have a perfect ending.

Check out my column “Front End Grocery store.”

Refer to the article

  • Prototype object