The new
keyword in JavaScript is one of these things that are often misunderstood or even feared by the people starting with JS.
JavaScript中的new
关键字是其中经常被JS入门的人们误解甚至恐惧的事物之一。
Things become much easier to understand once we check what thenew
is doing behind the scenes.
一旦我们检查了new
在幕后所做的事情,事情就会变得更容易理解。
In this article I will go through simple examples and show you what’s new
is doing for us behind the scenes.
在本文中,我将通过简单的示例,向您展示幕后为我们所做的new
工作。
Since ES6 we don’t see new
that often anymore but it’s still a must have knowledge for any dev.
从ES6开始,我们不再经常看到new
,但是对于任何开发人员来说,仍然是必不可少的知识。
The example
这个例子
Let’s use the very classic example.
让我们使用非常经典的示例。
Suppose we need a function that creates us an employee
object. We can do it like so:
假设我们需要一个创建employee
对象的函数。 我们可以这样做:
function createEmployee(name = "", position = "", age = 0) {
const employee = {};
employee.name = name;
employee.position = position;
employee.age = age; return employee;
}const exampleEmployee = createEmployee('Neko', 'FE dev', 30);// { name: 'Neko', position: 'FE dev' age: 30 }
We create an object, assign properties and return it at the end. As a side note, we should add some validation to it but it’s not the topic of this article.
我们创建一个对象,分配属性并最后返回它。 附带说明一下,我们应该对其进行一些验证,但这不是本文的主题。
How does new
can help us?
new
如何为我们提供帮助?
We can create a constructor
function — the convention is to start the name of the function from the capital letter i.e. EmployeeConstructor
and not employeeContructor
. It will work in both cases however.
我们可以创建一个constructor
函数-约定是从大写字母EmployeeConstructor
而不是employeeContructor
开头的函数名称。 但是,在两种情况下都可以使用。
function EmployeeConstructor(name = "", position = "", age = 0) { this.name = name; this.position = position; this.age = age;}const exampleEmployee = new EmployeeConstructor("Neko", "FE dev", 30);console.log(exampleEmployee);// EmployeeConstructor {name: "Neko", position: "FE dev", age: 30}
If you take a look inside the function EmployeeConstructor
you will notice that there is no return
statement, nor there is no object creation at the beginning, yet still we get the desired result.
如果您在EmployeeConstructor
函数内部进行查看,您会注意到没有return
语句,也没有开始的对象创建,但仍然可以得到理想的结果。
This happens thanks to the new
keyword, as it adds some implicit behaviour that we do not see i.e.
这要归功于new
关键字,因为它增加了一些我们看不到的隐式行为,即
- Creates an empty object. 创建一个空对象。
The empty object is binded to the
this
value.空对象绑定
this
值。The function will inherit from functionName.prototype.
该函数将从functionName 继承 。 原型 。
Returns the
this
if no explicitreturn
statement is used.如果不使用显式的
return
语句,则返回this
。A side note — if we try to
return
something else then object, array, or function, the constructor returnsthis
.注意:如果我们尝试
return
对象,数组或函数以外的其他内容,则构造函数将返回this
。This means that saying
这意味着说
return 'I am trying to break it'
would make thenew
to skip it and returnthis
instead.return 'I am trying to break it'
将使new
的跳过它并返回this
。
Here is a pseudocode to inspect what happens behind the scenes when we invoke function with new
keyword
这是一个伪代码,用于检查当我们使用new
关键字调用函数时幕后发生的情况
There is some technical jargon above i.e. __proto__
and prototype
.
上面有一些技术术语,例如__proto__
和prototype
。
If you aren’t familiar with constructors or prototypes, don’t worry about it too much for now. You’ll run into them sooner or later.
如果您对构造函数或原型不熟悉,那么现在就不必担心太多。 您迟早会遇到它们。
The important thing is, that the new object implicitly returned by the constructor function will be able to inherit properties and methods.
重要的是,构造函数隐式返回的新对象将能够继承属性和方法 。
If the keyword this
is confusing for you, I’ve got an article for you where I explain it in simple terms.
如果关键字this
是混淆了你, 我已经得到了你的文章 ,我深入浅出的讲解吧。
如果我们用new调用非构造函数会怎样? (What happens if we call non-constructor with new?)
To understand the new
even better, let’s go back to our initial example — the function that is not a constructor:
为了更好地理解new
,让我们回到最初的示例—不是构造函数的函数:
function createEmployee(name = "", position = "", age = 0) {
const employee = {};
employee.name = name;
employee.position = position;
employee.age = age; return employee;
}const exampleEmployee = new createEmployee('Neko', 'FE dev', 30);
What would happen if we would have invoked it with the new
keyword?That particular one would still work.
如果我们用new
关键字调用它会发生什么呢?
Why is that?
这是为什么?
Let’s add the extra things that new
does for us to the function.
让我们将new
的功能添加到函数中。
function createEmployee(name = "", position = "", age = 0) { /**
* this = {};
* this.__proto__ = EmployeeConstructor.prototype;
*/ const employee = {}; employee.name = name;
employee.position = position;
employee.age = age; // we are returning an object hence below is omitted by new
// return this; return employee;
}
As we can see, the following happens yet again:
如我们所见,以下再次发生:
The
new
keyword bindsthis
to a new object and sets its constructor and prototype.new
关键字this
绑定到新对象并设置其构造函数和原型。The
new
keyword adds logic that will returnthis
instead of a non-object.new
关键字添加了将返回this
逻辑而不是非对象的逻辑。The
new
keyword adds an implicitreturn this
statement at the end.new
关键字在末尾添加一个隐式return this
语句。
This doesn’t affect our code, since we don’t use the this
keyword in this function.
这不会影响我们的代码,因为我们不在此函数中使用this
关键字。
We also return an object, when we say return employee;
.In which case the returning logic and the return this
line is omitted.
当我们说return employee;
时,我们也返回一个对象return employee;
在这种情况下,返回逻辑和return this
行将被省略。
If we were using this
or if we weren’t returning an object, array or function, the function createEmployee
would behave differently when called with or without keywordnew
.
如果使用this
函数,或者不返回对象,数组或函数,则使用或不使用关键字new
调用函数createEmployee
行为都会有所不同。
Your turn
轮到你
Now you’ve got an understanding about the new
keyword. You know what it does behind the scenes for us.There is still more for you to explore i.e. investigate different edge cases.
现在,您已经对new
关键字有了一定的了解。 您知道它对我们幕后的作用。您还有更多探索的地方,例如研究不同的边缘情况。
翻译自: https://medium.com/@tymekluczko/the-new-keyword-in-javascript-f448b932eea8