Javascript 如何返回函数构造函数本身?
例如,我有一个函数构造函数Javascript 如何返回函数构造函数本身?,javascript,Javascript,例如,我有一个函数构造函数 let app = function(){ return new app(); }; 我想返回构造函数本身,但正如预期的那样,它会导致最大调用堆栈错误。下面有一个简单的方法 let app = function(){ return app.fn(); // or app.fn.init() anything like that (what jQuery does) } 我不知道什么是最好的或好的
let
app = function(){
return new app();
};
我想返回构造函数本身,但正如预期的那样,它会导致最大调用堆栈错误。下面有一个简单的方法
let
app = function(){
return app.fn(); // or app.fn.init() anything like that (what jQuery does)
}
我不知道什么是最好的或好的方法。所以我的目的还是希望尽可能简单地返回构造函数本身?当我调用app()
作为newapp()
时,它应该是相同的
另一个问题是“使用此方法是好是坏”如果您的意思是在调用
app
时需要一个实例,即使它不是通过new
调用的,您也应该在ES2015+中这样做:
let App = function() {
if (new.target) {
// Called as part of an instance creation operation, just return `this`
return this;
}
// Not called during instance creation, create an instance and return it
return new App();
};
或者对于较旧的ES5语法,您可能会使用instanceof
:
var App = function() {
if (this instanceof App) { // Is `this` an instance created by `App`?
// Yes, just return it
return this;
}
// No, create an instance and return it
return new App();
};
但是,我更喜欢要求以一致的方式调用函数(使用
new
或者不使用new
,但要一致)。通过使用类
语法,您可以得到一个内置的检查,确认该函数是作为实例创建操作的一部分调用的,因为它不允许通过[[Call]]而不是[[Construct]]调用构造函数。如果您的意思是在调用app
时想要一个实例,即使它不是通过new
调用的,您可以在ES2015+中执行此操作:
let App = function() {
if (new.target) {
// Called as part of an instance creation operation, just return `this`
return this;
}
// Not called during instance creation, create an instance and return it
return new App();
};
或者对于较旧的ES5语法,您可能会使用instanceof
:
var App = function() {
if (this instanceof App) { // Is `this` an instance created by `App`?
// Yes, just return it
return this;
}
// No, create an instance and return it
return new App();
};
但是,我更喜欢要求以一致的方式调用函数(使用
new
或者不使用new
,但要一致)。通过使用class
语法,您可以得到一个内置检查,确认该函数是作为实例创建操作的一部分调用的,因为它不允许通过[[Call]]而不是[[Construct]]调用构造函数。您想要一个实例化类的函数吗
// This is the class and constructor
const App = function() {
// This is a property
this.created = new Date()
// This is a method
this.age = function() {
return new Date() - this.created
}
}
// This creates the instance
const makeApp = function() {
return new App()
}
你想要一个实例化类的函数吗
// This is the class and constructor
const App = function() {
// This is a property
this.created = new Date()
// This is a method
this.age = function() {
return new Date() - this.created
}
}
// This creates the instance
const makeApp = function() {
return new App()
}
当您只想返回构造函数时,是否必须返回
app
,而不是newapp()
?你返回的实例应该是new app()
,但是当你执行new app()
操作时,这会返回一个实例……你能说明你想要实现什么吗?你的意思是当调用app
时你想要一个实例,即使它不是通过new
调用的吗?当你只想返回构造函数时,你不需要返回app
而不是newapp()
?就像你返回一个实例,它应该是一个new app()
,但是当你执行new app()
操作时,它会返回一个实例……你能说明你想要实现什么吗?你的意思是说,当调用app
时,你想要一个实例,即使它不是通过new
调用的?