JavaScript中的“ new”关键字

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 thenewis 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 newthat 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关键字,因为它增加了一些我们看不到的隐式行为,即

  1. Creates an empty object.

    创建一个空对象。
  2. The empty object is binded to the this value.

    空对象绑定this值。

  3. The function will inherit from functionName.prototype.

    该函数将从functionName 继承 原型

  4. Returns the this if no explicit return statement is used.

    如果不使用显式的return语句,则返回this

  5. A side note — if we try to return something else then object, array, or function, the constructor returns this.

    注意:如果我们尝试return对象,数组或函数以外的其他内容,则构造函数将返回this

    This means that saying

    这意味着说

    return 'I am trying to break it' would make the new to skip it and return this 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 newkeyword binds this to a new object and sets its constructor and prototype.

    new关键字this绑定到新对象并设置其构造函数和原型。

  • The newkeyword adds logic that will return this instead of a non-object.

    new关键字添加了将返回this逻辑而不是非对象的逻辑。

  • The newkeyword adds an implicit return 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 createEmployeewould 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值