gpt4 book ai didi

javascript - 在JavaScript中, "return"在函数构造函数中做什么

转载 作者:行者123 更新时间:2023-11-29 17:17:04 24 4
gpt4 key购买 nike

以下代码:

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 this

关于javascript - 在JavaScript中, "return"在函数构造函数中做什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16687229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com