在JavaScript中,"return"在函数构造函数中做
In JavaScript, what does "return" do in function constructor
以下代码:
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
因此,在这种情况下注释它将不会返回任何内容。
相关文章:
- ES6构造函数返回基类的实例
- 使用Google Visualization动态调用构造函数
- javascript中对象构造函数中的var属性与this.properties
- 理解typescript中的构造函数接口
- 为什么构造函数不是构造函数
- 如果在构造函数中有“返回”,则在 JavaScript 中的新运算符中做了什么
- 拦截对构造函数的调用
- 使用闭包共享构造函数参数
- 文本表示法VS.构造函数,用于在JavaScript中创建对象
- 从js引擎的角度来看闭包和构造函数是如何工作的
- 如何使用此从对象访问构造函数
- Javascript:为什么是构造函数's __proto__属性Empty(){}
- 当一个重要的构造函数参数丢失时应该发生什么
- Chrome Javascript日期构造函数错误
- 如何使用构造函数's的输出,以便将值插入到对象中
- 为什么"构造函数是一种特殊情况;
- "类“;常量和构造函数:如何实现
- "假的“;类构造函数中的参数
- "伪造“;JavaScript构造函数
- 匹配字符串“/$"在RegExp构造函数中