我正在尝试理清“new”关键字在 Javascript 中的工作方式。但它有一个奇怪的行为。
当我在节点中运行这段代码时:
var testing = function() {
self = this;
this.abc = 'abc';
console.log(this); // ====> 1
var subMethod = function () {
console.log(this); // =====> 2
console.log(self === this); // ====> 3
};
//subMethod.apply(this);
subMethod();
};
test = new testing();
// test = testing(); // ===> *4
console.log(self === this) 给我错误。
nr 1中的'this'是{abc:'abc'},sub方法中的'this'是全局'this'对象。谁能给我解释一下这种行为?
如果我使用 subMethod.apply(this) 运行,那么 console.log(self === this) 为真 ({ abc: 'abc' })
当我在不使用 new 关键字 (*4) 的情况下运行时,“this”变量与全局“this”相同(正如预期的那样),并且 console.log(self === this ) 是真的。
为什么子方法中的'this'与使用'new'关键字运行时的全局'this'相同。
最佳答案
当您调用 new testing()
时,函数 testing
将以其上下文 (this
) 作为新对象运行。第一个日志将是那个对象。在内部,当您运行 subMethod()
时,它是在全局上下文中运行的。 JS 就是这样做的。因此,this
是window
,并且self !== this
。如果您使用 this
上下文 (subMethod.apply(this)
) 调用它,那么很自然地 self === this
。
当您调用 testing()
时,它会在全局上下文中运行。当您添加 abc
时,它现在是全局的,因为 this
是 window
。当您调用 subMethod()
时,默认情况下也会在全局上下文中调用它,因此 self === this
。
所以基本上,运行普通函数是在全局上下文中。将函数作为构造函数运行(使用 new
)会创建一个新的上下文。在基础对象的上下文中调用运行方法(例如 "abaca".split('a')
)- split
是用 "abaca"调用的
作为它的 this
。
这有帮助吗?
关于子函数中的 Javascript new 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26861024/