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.
The so-calledFactory functionmeans 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)
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; }
As mentioned above, we can usenew
to classes or objects, then you may have the following questions:
new
keyword used in the factory function?new
keyword in the factory and constructor?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 thenew
keyword to create two objects using the factory and constructor at the same time, and then print the two objects on the console.
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);
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 themike
object above, let's do a simple===
equality check.
Well, interestingly, it points toObject.prototype
. Okay, let's do the same experiment with the constructor.
Before understanding the prototype, you need to remember the following knowledge:
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)
Note: In JavaScript, these constructs Functions are also called constructorbecause 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);
When we expand the__proto__
of the first layer, there is another__proto__
inside it, we expand it again it.
Now let’s try to figure out if the prototype object looks like above.
他们是不同的。 当我们使用工厂函数创建对象时,它的__proto__
指向Object.prototype
,而当从构造函数创建对象时,它指向它的构造函数原型对象。 那么这里发生了什么?
当我们在创建对象时使用带有构造函数的new
关键字时,new
背后所做的事不多。
new运算符创建一个用户自定义的对象类型的实例或具有构造函数的内置对象的实例。new关键字会进行如下操作:
注释行是伪代码,表示在 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关键字,对输出都没有影响。
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);
然后,如果查看创建的对象实例,你希望看到什么?
发生了什么? 使用new
运算符,正如我们所期待的一样输出正确的对象,但没有new
运算符,结果是undefined
怎么可能呢?
如果你对JavaScript 作用域和this
关键字的工作原理有所了解,那么你可以猜到这里发生了什么? 让我们来看看。
看起来我们传递给没有new
关键字的函数的所有属性都已设置为window
对象。 那是因为到那个时候函数内部的这个变量引用了global或window
对象,基本上我们在这里做的就是污染了全局对象。
这是你可以对你的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!