尝试创建返回函数的对象?

Jyo*_*may 0 javascript oop

我尝试了不同的东西,最终得到了这些代码..

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(); 
Run Code Online (Sandbox Code Playgroud)

这是投掷错误??!of2.inner不是一个函数

所以,我的匿名函数将相同的函数体返回给我的变量.为什么我仍然无法实例化?

Gol*_*rol 5

第一部分返回一个可以调用该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();
Run Code Online (Sandbox Code Playgroud)