什么是返回新函数();在 JavaScript 中? [英] What is return new function(); in JavaScript?

查看:20
本文介绍了什么是返回新函数();在 JavaScript 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 js 代码中我见过这样使用:

In js code I have seen this used:

function doStuff( selector ) {
    /* Stuff to do with selector */
}

var q = function( selector ) {
    return new doStuff( selector );
}

到底发生了什么?return new 到底在做什么?它似乎将它的参数传递给另一个函数,但是请有人能引导我完成这个过程吗?

What exactly is happening? What is return new really doing? It seems to pass its arguments to the other function, but would someone please be kind enough to walk me through the process?

感谢所有和任何帮助,在此先感谢.

All and any help is appreciated, thanks in advance.

推荐答案

当我们使用 new 关键字调用函数时.会发生以下情况:

When we call a function with the new keyword. the following will happen:

  • 将在内存中创建一个 new 对象
  • 该对象的范围将被传递给函数;所以 this 关键字将引用该对象.
  • 将返回新创建的对象.

本质上,这就是您在 JavaScript 中创建实例的方式.您需要使用 new 关键字调用函数.这样做时,该函数称为构造函数.

So in essence, that is how you create instances in JavaScript. You need to call a function with the new keyword. When doing so, the function is called constructor.

在您的示例中,q 函数返回 doStuff 方法的实例.请记住,命名约定是不正确的.

In your example, the q function returns an instance of the doStuff method. Bare in mind though that the naming convention is not correct.

构造函数应该是名词而不是动词,它们应该是帕斯卡格,而不是骆驼格

Constructors should be nouns rather that verbs and they should be in Pascal-case, not camel-case

这篇关于什么是返回新函数();在 JavaScript 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆