什么是return new function();在JavaScript中? [英] What is return new function(); in JavaScript?

查看:272
本文介绍了什么是return new function();在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关键字将指向该对象.
  • 将返回新创建的对象.
  • A new object will be created in the memory
  • The scope of that object will be passed to the function; So the this keyword will refer to that object.
  • The newly created object will be returned.

因此,从本质上讲,这就是在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.

构造函数应该是名词而不是动词,并且应该以Pascal大小写,而不是驼峰大小写

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

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

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