Translator: Front-end wisdom

Original text: medium.com/@chamikakas…

Click “like” and then look, wechat search [Big Move the world] pay attention to this person without dACHang background, but with a positive attitude upward. In this paper, making github.com/qq449245884… Has been included, the article has been categorized, also organized a lot of my documentation, and tutorial materials.

Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.

One of the confusing things you might hear when talking about the JavaScript language compared to other programming languages is factory functions and constructors.

To read more quality articles pleaseJabber at the GitHub blog, a hundred quality articles a year waiting for you!

The factory function

By factory functions, you mean that these built-in functions are class objects, and when you call them, you actually create an instance of the class. What that means is that when I call this function, I’m actually creating an object with the class and then returning the object. Since Javascript itself is not a strict object-oriented language (it does not contain classes), there are no strict “factory functions” in Javascript, but in Javascript we can use functions to simulate classes. Consider the following example:

function person(firstName, lastName, age) {
  const person = {};
  person.firstName = firstName;
  person.lastName = lastName;
  person.age = age;
  return person;
}
Copy the code

This code creates a new object, appends the pass parameter as a property to the object and returns the new object. This is a simple JavaScript factory function.

In fact, the factory function is easy to understand:

  1. It’s a function.
  2. It is used to create objects.
  3. Like a factory, it “produces” functions that are “standard parts” (with the same properties)

The constructor

Unlike other mainstream programming languages, JavaScript’s constructor does not exist as a specific method of a class; When any ordinary function is used to create a class of objects, it is called a constructor, or constructor. To be a true constructor, a function must satisfy the following conditions:

  1. The properties of the new object (this) are set inside the function, usually by adding properties and methods.

  2. Constructors can contain return statements (not recommended), but the return value must be this, or some other value that is not of an object type.

    function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; }

Use the new keyword to create an object

As mentioned above, we can use new for classes or objects, then you may have the following problems:

  1. Can we use the new keyword in the factory function?

  2. What happens if we use the new keyword in the factory and constructor

  3. What happens if you do not use the new keyword when creating object instances using constructors

Ok, so before we try to figure that out, let’s do a little exercise to understand what’s going on here.

Use the new keyword to create two objects using both the factory and the constructor, and then print both objects on the console.

Using factory functions

function person(firstName, lastName, age){
  const person = {}
  person.firstName = firstName;
  person.lastName = lastName;
  person.age = age;
  return person;
}

const mike = new person('mike', 'grand', 23);
Copy the code

As we saw above, where __proto__ is a pointer to its prototype object, let’s try to figure out what the prototype object is. To find out where the Mike object above points to the prototype object, let’s do a simple === equation check.

Well, interestingly, it points to Object.prototype. Ok, let’s do the same experiment with constructors.

Understand JavaScript prototypes

Here are a few things to keep in mind before you understand the prototype:

  • All reference types (arrays, objects, functions) have object properties and are free to extend attributes (except null)
  • All reference types (arrays, objects, functions) have a __proto__ attribute whose value is a normal object
  • All functions have a prototype property whose value is also a normal object
  • For all reference types (arrays, objects, functions), the __proto__ property value points to the prototype property value of its constructor

To explain this in code:

Var obj = {}; var obj = {}; obj.a = 100; var arr = []; arr.a = 100; function fn () {} fn.a = 100; __proto__ console.log(obj.__proto__); console.log(arr.__proto__); console.log(fn.__proto__); Prototype console.log(fn. Prototype) The __proto__ attribute value of the reference type points to the prototype attribute value of its constructor console.log(obj.__proto__ === object.prototype)Copy the code

Using constructors

Note: In JavaScript, these constructors are also called constructor because they are used to create objects.

function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
}
const mike = new Person('mike', 'grand', 23);
Copy the code

When we expand the __proto__ of the first layer, it has another __proto__ inside it, which we extend again.

Now let’s try to figure out if the prototype object looks like this.

They are different. When we create an Object using a factory function, its __proto__ points to object. prototype, and when we create an Object from a constructor, it points to its constructor prototype Object. So what’s going on here?

The thing behind new

When we use the new keyword with a constructor when creating objects, there’s not much behind new.

The new operator creates an instance of a user-defined object type or of a built-in object with a constructor. The new keyword does the following:

  1. Create an empty simple JavaScript object (that is {})

  2. Link this object (that is, set its constructor) to another object

  3. Use the new object created in Step 1 as the context for this

  4. If the function does not return an object, this is returned

The comment line is pseudocode that does something for us behind the new keyword, JS.

function Person(firstName, lastName, age) {
    // this = {};
    // this.__proto__ = Person.prototype;

    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    
    // return this;
}
Copy the code

Also, let’s see what happens if we add the above implicit code to the factory function.

function person(firstName, lastName, age) {
    // this = {};
    // this.__proto__ = Person.prototype; 
 
  
    const person = {};
    person.firstName = firstName;
    person.lastName = lastName;
    person.age = age;
    return person;
    
    // return this;
}
Copy the code

Even if implicit code is added to the factory function when using the new keyword call, it will have no effect on the results. This is because, since we are not using the this keyword in our function, and we explicitly return a custom object other than this, there is no need to use implicit code. Whether or not we use the new keyword for the factory function has no effect on the output.

If you forgetnewWhat about keywords

There are many concepts in JavaScript that are sometimes difficult to grasp. The new operator is one of them. If you don’t understand it correctly, it can have nasty consequences when running JavaScript applications. In languages like Java, there are strict restrictions on how the new keyword can be used. But in javascript, it’s not that strict, and it can cause a lot of problems if you don’t understand them correctly.

In JavaScript:

  • You can use the new operator on any function

  • Functions can be called as constructors with or without the new keyword

Let’s look at the example above, the key case with and without new

function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } const mike = new Person(‘mike’, ‘grand’, 23); const bob = Person(‘bob’, ‘grand’, 23);

Then, if you look at the created object instance, what do you want to see?

What happened? Using the new operator, it prints the correct object as expected, but without the new operator, the result is undefined.

If you know something about how the **JavaScript scope ** and this keyword work, then you can guess what’s going on here? Let’s take a look.

It looks like all the properties we pass to functions without the new keyword are set to window objects. That’s because at that point the variable inside the function refers to the global or window object, and basically what we’re doing here is polluting the global object.

This is a really nasty thing you can do to your JavaScript programs. Therefore, using the new operator, the JavaScript engine sets the this variable to refer to the newly created object instance, which is why we can see that all the properties passed to the constructor are set to Mike.

But when the constructor is called without the new operator, the JavaScript engine interprets this as a regular function call and returns undefined without an explicit return statement. This is why it is crucial to understand how the new operator works in JavaScript.

communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.