我正在尝试弄清'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'},子方法中的'this'是全局的'this'对象。谁能给我这个行为的解释?
如果我使用subMethod.apply(this)运行,那么console.log(self === this)为true({abc:'abc'})
当我不使用new关键字(* 4)运行时,'this'变量就是与全局“ this”相同(如预期),console.log(self === this)也为true。
当使用'new'关键字运行时,子方法中的'this'为什么与全局'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
。
有帮助吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句