我尝试了一些不同的东西,最终得到了这些代码..
var f1 = function() {
this.x = 10;
this.innerf = function() { console.log(this.x); }
}
var of1 = new f1();
of1.innerf();
var f2 = function() {
return function() {
this.x = 10;
this.innerf = function() { console.log(this.x); }
}
}
var of2 = new f2();
of2.innerf();
抛出错误??! of2.inner 不是一个函数
因此,我的匿名函数将相同的函数体返回给我的变量。 为什么我仍然无法实例化?
最佳答案
第一部分返回一个对象,您可以调用该对象 innerf
方法。
第二部分返回一个函数,如果调用它,该函数将返回一个对象。但你没有。
这会起作用。调用函数 f2()。它的返回值是匿名函数。然后,用new <return value of f2>()
,您可以创建该对象的实例。
var f2 = function() {
return function() {
this.x = 10;
this.innerf = function() { console.log(this.x); }
}
}
var of2 = new (f2())();
of2.innerf();
// The two lines above can also be written as:
var of3constructor = f2(); // This returns the inner anonymous function.
var of3 = new of3constructor(); // This creates an instance by invoking the anonymous function.
of3.innerf();
关于javascript - 尝试创建返回函数的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31013207/