Pick up the book and start to learn the front end (Part 2)

Object the Object –

How many questions should we start with?

  • 1. What is object orientation?
  • 2. Is function an object?
  • 3. How many types of objects are there?
  • 4. What is a prototype object?
  • What the hell is a constructor?
  • 7. What did New do?

Think back to this. Do you know the answers to these questions? In the following content, let’s learn one by one together!

Is article

Soul questioning? What exactly is JS

JavaScript (” JS “for short) is a function-first, lightweight, interpreted or just-in-time compiled programming language. Although it is best known as a scripting language for developing Web pages, iT is also used in many non-browser environments. JavaScript is a prototype-based, multi-paradigm dynamic scripting language, and supports object-oriented, imperative, and declarative (such as functional) programming styles.

Baidu is so said, this is not human words, in fact, js is essentially what?

Js is a language designed to write web interaction behavior

That js is composed of what, say simply with respect to a word

ECMAScript + webAPI – ECMASciript -Object is an ES language standard

What is an object-object?

Objects actually have two characteristics

  • 1. A program structure that describes the properties and functions of a concrete thing in reality
  • Memory A block of storage space in which multiple data and methods are stored simultaneously.

Since objects are properties and functions of a concrete thing. Then, properties of things become properties of objects, and functions of things become methods of objects

What is object orientation?

In the program, the object is used to encapsulate the attributes and functions of a thing. The task is then performed by calling the object’s methods. This is object-oriented, in fact, before ES6 came out, JS always seems so social, other languages should have object structure, he is a did not touch, know ES6 suddenly born, we have the concept of class, object-oriented is also officially started!

What is the underlying object?

Since this is the re-learning front end, we are not going to talk about how to create objects like baidu search can have 100 pages of answers.

Let’s explore, what is the underlying object? Before we dive into the underlying layer, let’s look at arrays

An array of

Array objects are used to store a list of values using a single variable name.

Arrays, it can be classified into ordinary arrays, two-dimensional arrays, hash arrays, ordinary arrays, and two-dimensional arrays. I’m not going to go into that, but let’s talk about this hash array

The hash array

Hash array, also known as associative array, as the name implies, his array elements are composed of [key: value]

var myhash = new Array();
myhash['new'] = 'newval';
myhash['new2'] = 'newval_2';
Copy the code

The result of this code is the data structure of the hash array

And you notice that our objects can also be assigned and evaluated this way

In the figure below, we find that we can also use the above method to assign and value objects

The underlying object is a hash array
Objects are highly dynamic, and JavaScript gives users the ability to add state and behavior to objects at run time. (Big guy’s summary, I copy)

Two classes of attribute characteristics for an object

When we think of objects as simple key-value pairs, when we dig deeper, we find that objects also provide some characteristics that describe our object members

1. Describe the characteristics of data attributes

  • Value: indicates the value of the attribute.
  • Writable: Determines whether a property can be assigned a value.
  • Enumerable: Determines if for in can enumerate this property.
  • Different: Determines whether the property can be deleted or changed.

1. Describe the characteristics of accessor properties

  • Getter: Function or undefined, called when fetching a property value.
  • Setter: function or undefined, called when setting property values.
  • Enumerable: Determines if for in can enumerate this property.
  • Different: Determines whether the property can be deleted or changed.

Normally, we don’t need these things, we just need to worry about assignments and values, so what do you want me to do?

We can use the built-in Object. GetOwnPropertyDescripte to view

  var actions = {
            b: 1,
            c: 2
        }
        var d = Object.getOwnPropertyDescriptor(actions, "b")
        console.log(d)
Copy the code

The results are as follows

If you want to modify it, you can do so using the built-in Object.defineProperty, which is how Vue works with data hijacking

 var value = { a: 1 };
        Object.defineProperty(value, "b", { value: 2, writable: false, enumerable: false, configurable: true });

        var obja = Object.getOwnPropertyDescriptor(value, "a");
        var objb = Object.getOwnPropertyDescriptor(value, "b"); Value. B = 3; console.log(value.b, obja, objb); / / 2Copy the code

So how did he pull off the data hijacking? Don’t rush into it

        var value = { b: 1 };
        var tm = null;
        Object.defineProperty(value, "b",
            {
                get: function () {
                    console.log('I got called once when I evaluated.')
                    return tm
                },
                set: function (a) {
                    console.log('Get called once when I assign.') tm = a } }); // assign value.b = 3; / / value of the console. The log (value. B);Copy the code

The core of vue responsiveness is object.defineProperty, which listens for value changes and notifies subscribed methods to change views

Object-oriented inheritance

Speaking of object orientation, inheritance is essential, so what is inheritance?

In plain English: inheritance is a member of the parent object. The child object can be used directly without being created

So how do we inherit?

The prototype object implements inheritance

Before ES6, we did not have the concept of classes, so our language standard followed the prototype system invented by our ancestors. Although it is not the appearance of orthodox language, it is also unique. Can we call js if everything looks like Java?

A prototype is where the new object holds a reference to the common properties and methods. Note that the new object does not actually copy a prototype object. Instead, the new object is made to hold a reference to the prototype.

The above concept answers the question of what a prototype object is. Here’s another cliche name: constructors

The constructor

Constructor: A special function that defines the uniform structure of a class of objects.

The relationship between constructors and prototypes and objects is shown below:

proto
prototyoe

 functionPerson(name) { this.name = name; } // Use the constructor's Person prototype property to find the prototype object person.prototype.eat =function () {
            console.log("Eat");
        }

        let Person1 = new Person("aaa", 24);
        let Person2 = new Person("bbb", 24); Console. log(person1.eat === person2.eat)// Find equality console.log(Person1) console.log(Person2)Copy the code

Prototype chain

After understanding the above principles, we can easily find that the implementation of the current popular constructor inheritance, composite inheritance, prototype inheritance, parasitic inheritance, parasitic combinatorial inheritance is actually just changing his. Of course, with ES6 in the air today, we have class and extends that kill all the bells and whistles!

   class Animal {
            constructor(name) {
                this.name = name;
            }
            speak() {
                console.log(this.name + ' makes a noise.');
            }
        }
        class Dog extends Animal {
            constructor(name) {
                super(name); // call the super class constructor and pass in the name parameter
            }
            speak() {
                console.log(this.name + ' barks.'); }}let d = new Dog('Mitzie');
        d.speak(); // Mitzie barks.
Copy the code

With these concepts in mind, let’s answer the above question, what exactly does New do?

What did New do?

I understand this new keyword actually does four things, also very easy to remember

  • Create an empty object
  • Set the new object’s __proto__ inheritance constructor to the prototype object
  • Calling the constructor with a new object, replacing this in the constructor with an empty object will add new properties and methods to the empty object.
  • Return the object address to OBj

As mentioned above, this points to the problem and I’ll sort out a few cases

This points to the

There are four binding rules for this.

  • 1. Default binding, implicit binding (strict/non-strict mode)
  • 2. Explicit binding
  • 3. New binding
  • 4. Arrow function binding

First declare: this is determined at run time. That is, when the function is called, the call location is where the function is called in the code (not the declared location).

In fact, my understanding is that this is already determined when the function is pushed into the execution environment stack, and when it is executed, it simply replaces this with an object pointing to the place where this has been determined. Specially went to the Internet to check a lot of information is also a variety of versions, here to say my understanding, wrong place please big guy pointed out)

The default binding

The default is to point to the object calling this method, if there is no object to call, then you don’t have to think about it, it points to the global, if it is strict mode, undefined

function foo() { console.log( this.a ); } var obj = { a: 2, foo: foo }; // We noticed that the previous object called obj.foo(); / / 2Copy the code
 
 var obj = {
            b: function() { console.log(this); }}function}2 b(obj.b)//windowCopy the code

Explicitly bound

Bind this to call, apply, and bind to call, apply, and bind to call, apply, and bind to call, apply, and bind

function foo() { console.log( this.a ); } var obj = { a: 2 }; foo.call( obj ); // 2 uses call to force bindingCopy the code

The new binding

functionfoo(a) { this.a = a; } var bar = new foo(2); // When new, this is bound to the new object console.log(bar.a); / / 2Copy the code

Arrow function binding

A new special function type is added in ES6: arrow functions. Arrow functions cannot use the above rules

Var foo =()=> {console.log(this)} var a = {b: foo} a.b()//windowCopy the code

This binding, in fact, the statement has been identified as the current context of this scope of environment (at the time was the bosses asked ali, this arrow function when certain, my understanding is also a time when pressed into the environment of the stack, to determine the scope, then at the time of execution from the scope of environment to get this, That is, it is bound when declared, and does not correct.

All kinds of objects

We all know that everything is an object, but in fact in JS objects are also divided into categories, in addition to the ordinary objects we usually know we have host objects, built-in objects to explain one by one

Host Objects

Objects provided by the JavaScript host environment whose behavior is entirely determined by the host environment.

The host object is where our JS is running and the object that it provides, and the one that we’re most familiar with is the browser environment, and our host object is the Window, and that window contains all sorts of different things that come from JavaScript and comes from the browser environment.

Built-in Objects

Built-in objects include native objects and native objects

Intrinsic Objects

A native object is an instance of an object that is automatically created as the JavaScript runtime creates it, as specified by the standards.

Native objects are created before any JS code is executed, and they often act like base libraries. Some of the JS methods we use are actually native objects

Native Objects

Objects that can be created by the user using built-in constructors such as Array, RegExp, or special syntax.

We refer to JavaScript objects that can be created through the language’s own constructor as native objects. In the JavaScript standard, there are more than 30 constructors that allow you to create new objects with a new operation, so we call these objects native.

At this point, we see that a function is actually an object, and that answers the question I asked at the beginning, so let’s verify that

 function foo() {

        }
        foo.b = 3
        console.log(foo)
        console.log(foo.b)//3
Copy the code

It turns out that I can actually assign a property to a function, which is a privilege only objects can have, so it’s also an object

Write in the last

A systematic study of the object in the end is what, and answered the above several questions. Thanks again for geek big guy’s heavy learning front end, let me know JS again, record learning, wrong place, welcome big guy correct!

Finally, we are left with a big guy who queries the native object code. He lists all js objects that contain native objects with three values:

Infinity, NaN, undefined.

Nine functions:

  • eval
  • isFinite
  • isNaN
  • parseFloat
  • parseInt
  • decodeURI
  • decodeURIComponent
  • encodeURI
  • encodeURIComponent

** Some constructors: **

Array, Date, RegExp, Promise, Proxy, Map, WeakMap, Set, retry Set, Function, Boolean, String, Number, Symbol, Object, Error, EvalError, RangeError, ReferenceError, SyntaxError

TypeError

URIError, ArrayBuffer, SharedArrayBuffer, DataView, Typed Array, Float32Array, Float64Array, UInt8Array, Int16Array, Int32Array, UInt8Array, UInt16Array, UInt8ClampedArray

Four objects used as namespaces:

Atomics JSON Math Reflect

 var set = new Set();
        var objects = [
            eval,
            isFinite,
            isNaN,
            parseFloat,
            parseInt,
            decodeURI,
            decodeURIComponent,
            encodeURI,
            encodeURIComponent,
            Array,
            Date,
            RegExp,
            Promise,
            Proxy,
            Map,
            WeakMap,
            Set,
            WeakSet,
            Function,
            Boolean,
            String,
            Number,
            Symbol,
            Object,
            Error,
            EvalError,
            RangeError,
            ReferenceError,
            SyntaxError,
            TypeError,
            URIError,
            ArrayBuffer,
            SharedArrayBuffer,
            DataView,
            Float32Array,
            Float64Array,
            Int8Array,
            Int16Array,
            Int32Array,
            Uint8Array,
            Uint16Array,
            Uint32Array,
            Uint8ClampedArray,
            Atomics,
            JSON,
            Math,
            Reflect];
        objects.forEach(o => set.add(o));
        for (var i = 0; i < objects.length; i++) {
            var o = objects[i]
            for (var p of Object.getOwnPropertyNames(o)) {
                var d = Object.getOwnPropertyDescriptor(o, p)
                if((d.value ! == null && typeof d.value ==="object") || (typeof d.value === "function"))
                    if(! set.has(d.value)) set.add(d.value), objects.push(d.value);if (d.get)
                    if(! set.has(d.get)) set.add(d.get), objects.push(d.get);if (d.set)
                    if(! set.has(d.set)) set.add(d.set), objects.push(d.set); } } console.log(set) / / 441Copy the code