如果使用带有new
的函数(从而创建了一个对象实例)并从该函数返回,则返回值将用作new
的结果,而不是该对象实例.当您返回一个函数并在没有绑定到上下文的情况下直接调用它时,它的上下文在浏览器中为window
:
如果构造函数返回非原语,则此返回值将成为整个新表达式的结果.否则,如果构造函数不返回任何内容或返回原语,则返回newInstance.(通常,构造函数不返回值,但它们可以 Select 这样做以覆盖正常的对象创建过程.)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new个
function outer(abc) {
this.abc = abc;
return function inner() {
console.log(this);
this.abc = abc;
return this.abc;
}
}
console.log((new outer)());
要修复您的代码,只需删除对this
的依赖:
function outer(abc) {
this.abc = abc;
return function inner() {
return abc;
}
}
console.log((new outer(123))());
Anyway I think your pattern here doesn't make much sense. Seems you want to achieve a pattern that would be done much cleaner and easier.
And to be more specific @VLAZ has pointed that this.abc = abc;
in the outer class is pointless since not used later, that I noticed also but avoided to gain some focus on it. Ok as a part of JS learning though...
@silentmantra请澄清下面代码中的一个疑问,我一定会接受您的回答.为什么我不能创建内部函数的对象,而它不返回任何东西.函数OUTER(Abc){this.abc=abc;返回函数INTERNAL(){this.abc=abc;}}var RESULT=new out(23)();sole.dir(Result);
如上所述,当您调用返回的函数时,您将丢失this
上下文,它将变为window
(默认上下文).所以基本上返回了window.abs
,而你赋值给它之后就是11
了.
而你最后的console.log(obj2.abc)
没有意义,因为你试图得到一个数字的props :
function outer(abc) {
this.abc = abc;
return function inner() {
this.abc = abc;
return this.abc;
}
}
var obj2= new outer(11)();
console.log(obj2)
console.log(obj2.abc) // 11 doesn't have 'abs' property
console.log(window.abc) // oops, but window has
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this个