What is return new function(); in JavaScript?(什么是返回新函数();在 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 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是返回新函数();在 JavaScript 中?


- Fetch API 如何获取响应体? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01