Home >Web Front-end >JS Tutorial >A brief discussion on factory functions and constructors in JavaScript

A brief discussion on factory functions and constructors in JavaScript

青灯夜游
青灯夜游forward
2020-11-30 18:05:494221browse

A brief discussion on factory functions and constructors in JavaScript

When it comes to the JavaScript language compared to other programming languages, you may hear some confusing things, one of which is factory functions and constructors.

Factory function

The so-called Factory function means that these built-in functions are class objects. When you call them, "A class instance is actually created". This means that when I call this function, I actually create an object using the class and then return the object. Since Javascript itself is not a strict object-oriented language (does not contain classes), Actually, Javascript does not have a strict "factory function", but in Javascript, we can use functions to simulate classes. Let's look at the following example:

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

The above code creates a new object and passes it The parameters are attached to the object as properties and the new object is returned. This is a simple JavaScript factory function.

In fact, the factory function is also easy to understand:

  • It is a function.

  • It is used to create objects.

  • It is like a factory, "produced" The functions are all "standard parts" (have the same attributes)

Constructor

Different from other mainstream programming languages, JavaScript The constructor does not exist as a specific method of the class; when any ordinary function is used to create a class of objects, it is called a constructor, or constructor. For a function to be a true constructor, The following conditions need to be met:

  • Set the properties of the new object (this) inside the function, usually by adding properties and methods.

  • The constructor can contain a return statement (not recommended), but the return value must be this, or other non-object type value.

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 to classes or objects, then you may have the following questions:

  1. We can Is the new keyword used in the factory function?
  2. What happens if we use the new keyword in the factory and constructor?
  3. If in What happens when you create an object instance using a constructor without using the new keyword

Okay, before trying to find out the answer to the above question, let’s do a small exercise to understand what’s going on here .

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

Use the factory function

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);

A brief discussion on factory functions and constructors in JavaScript

As we have seen above, here __proto__ is a pointer to its prototype object, let us try to find out What is the prototype object. In order to find out the prototype object pointed to by the mike object above, let's do a simple === equality check.

A brief discussion on factory functions and constructors in JavaScript

Well, interestingly, it points to Object.prototype. Okay, let's do the same experiment with the constructor.

Understanding the prototype of JavaScript

Before understanding the prototype, you need to remember the following knowledge:

  • All reference types (arrays, Objects, functions), all have object characteristics, which can be freely extended attributes (except null)
  • All reference types (arrays, objects, functions) have a __proto__ attribute, and the attribute value is an ordinary Object
  • All functions have a prototype attribute, and the attribute value is also an ordinary object
  • For all reference types (arrays, objects, functions), the __proto__ attribute value points to it The prototype attribute value of the constructor

Explain it through the code:

// 要点一:自由扩展属性
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)

// 要点四:引用类型的 __proto__ 属性值指向它的构造函数的 prototype 属性值
console.log(obj.__proto__ === Object.prototype)

Using the constructor

Note: In JavaScript, these constructs Functions 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);

A brief discussion on factory functions and constructors in JavaScript

When we expand the __proto__ of the first layer, there is another __proto__ inside it, we expand it again it.

A brief discussion on factory functions and constructors in JavaScript

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

A brief discussion on factory functions and constructors in JavaScript

他们是不同的。 当我们使用工厂函数创建对象时,它的__proto__指向Object.prototype,而当从构造函数创建对象时,它指向它的构造函数原型对象。 那么这里发生了什么?

new 背后所做的事

当我们在创建对象时使用带有构造函数的new关键字时,new 背后所做的事不多。

new 运算符创建一个用户自定义的对象类型的实例或具有构造函数的内置对象的实例。 new 关键字会进行如下操作:

  1. 创建一个空的简单 JavaScript 对象 (即 {})
  2. 链接该对象(即设置该对象的构造函数)到另一个对象
  3. 将步骤1新创建的对象作为 this 的上下文
  4. 如果该函数没有返回对象,则返回 this

注释行是伪代码,表示在 new 关键字,JS 背后帮我们做的事情。

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

    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    
    // return this;
}

另外,让我们看看如果将上面的隐式代码添加到工厂函数中会发生什么。

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;
}

即使使用new关键字调用时将隐式代码添加到工厂函数中,也不会对结果产生任何影响。这是因为,由于我们没有在函数中使用 this 关键字,而且我们显式地返回了一个除this之外的自定义对象,因此没有必要使用隐式代码。无论我们是否对工厂函数使用new关键字,对输出都没有影响。

如果忘记了 new 关键字怎么办

JavaScript 中有许多概念,有时难以掌握。 new 操作符就是其中之一。 如果你不能正确理解它,那么在运行 JavaScript 应用程序时会产生令人讨厌的后果。 在像 Java这 样的语言中,严格限制了如何使用 new 关键字。 但是在 javascript 中,并不是那么严格,如果你不能正确理解它们可能会导致很多问题。

在 JavaScript 中:

  • 可以对任何函数使用 new 运算符
  • 可以使用或不使用 new 关键字将函数作为构造函数调用

让我们看看上面的例子,使用和不使用 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);

然后,如果查看创建的对象实例,你希望看到什么?

A brief discussion on factory functions and constructors in JavaScript

发生了什么? 使用 new 运算符,正如我们所期待的一样输出正确的对象,但没有new运算符,结果是undefined 怎么可能呢?

如果你对 JavaScript 作用域 this 关键字的工作原理有所了解,那么你可以猜到这里发生了什么? 让我们来看看。

A brief discussion on factory functions and constructors in JavaScript

看起来我们传递给没有new关键字的函数的所有属性都已设置为window对象。 那是因为到那个时候函数内部的这个变量引用了globalwindow 对象,基本上我们在这里做的就是污染了全局对象。

这是你可以对你的JavaScript程序做的非常讨厌的事情。 因此,使用new运算符,JavaScript引擎将this 变量设置为引用新创建的对象实例,这就是为什么我们可以看到传递给构造函数的所有属性都已设置为 mike

但是在没有new运算符的情况下调用构造函数的情况下,JavaScript 引擎会将 this 解释为常规函数调用,而没有显式返回语句时返回undefined。 这就是理解new 运算符在JavaScript中的工作原理非常关键的原因。

原文地址:https://medium.com/@chamikakasun/javascript-factory-functions-vs-constructor-functions-585919818afe

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of A brief discussion on factory functions and constructors in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete