在JavaScript中,什么是;return";函数构造函数中的do
以下代码:在JavaScript中,什么是;return";函数构造函数中的do,javascript,constructor,Javascript,Constructor,以下代码: function A() { this.method_this_outsideReturn = function() { console.log('method_this_outsideReturn') }; return { method_this_insideReturn: function() { console.log('method_this_insideReturn') },
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
语句,但是如果没有明确包含它,它将返回未定义的
因此,在这种情况下,注释它将不会返回任何结果。因为您有一个返回,而不是接收返回,并反对您接收返回的内容
因此a将不是对象,而是方法\u此\u内部返回,因此您将无法再从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());
您正在使用显示模块模式,请参见。您正在将逻辑封装到函数(函数a())中<代码>返回
在constructor中应该只返回此
。但是在您的示例中,它与构造函数无关,它与从Javascript中的任何函数返回值相同。如果构造函数返回值,则返回的值将被视为创建的对象,如果你没有return语句,它会假设它是return this
他正在做关于构造函数的事情,所有答案都非常有用,但这正是我要找的。谢谢相关问题非常相关。谢谢!