在JavaScript中,"return"在函数构造函数中做

In JavaScript, what does "return" do in function constructor

本文关键字:quot 构造函数 函数 return JavaScript      更新时间:2023-09-26

以下代码:

function A() {
    this.method_this_outsideReturn = function() {
        console.log('method_this_outsideReturn')
    };
    return {
        method_this_insideReturn: function() {
            console.log('method_this_insideReturn')
        },
    };
}
var a = new A();
console.log(a.method_this_insideReturn()); // This would work.
console.log(a.method_this_outsideReturn()); // This wouldn't work. Warns attri_this_outsideReturn undefined

但是,在注释掉返回值后:

function A() {
    this.method_this_outsideReturn = function() {
        console.log('method_this_outsideReturn')
    };
    /*return {
        method_this_insideReturn: function() {
            console.log('method_this_insideReturn')
        },        
    };*/
}
console.log(a.method_this_outsideReturn()); // This would work now

为什么会这样?return在构造函数中做什么?当return语句不存在时会发生什么?

如果你的构造函数返回一个值,返回的值将被认为是创建的对象,如果你没有返回语句,它将假定它是return this

因为你有一个返回,而不是接收返回和对象接收您返回的任何东西。

所以a将不是一个对象,它将是method_this_insideReturn,所以你将无法从a访问你的本地方法,因为它们不存在。

我不知道你为什么要添加返回,但最好是使它成为一个局部方法,然后访问它。

   function A() {
        this.method_this_outsideReturn = function() {
            console.log('method_this_outsideReturn')
        };
        this.method_this_insideReturn: function() {
                console.log('method_this_insideReturn')
            }        
    }
console.log(a.method_this_outsideReturn());
console.log(a.method_this_insideReturn());

您正在使用揭示模块模式,请参阅https://stackoverflow.com/a/5647397/874927。将逻辑封装在函数(函数a())中。构造函数中的return应该只返回this。然而,在您的示例中,它与构造函数无关,它与Javascript中任何函数的返回值相同。

每个函数/方法调用将有一个return语句,但是如果它没有明确包含,它将return undefined

因此,在这种情况下注释它将不会返回任何内容。