请帮助获得答案我不明白为什么定义后上下文丢失
class A {
func() {
console.log(this)
}
}
let a = new A();
let b = a.func;
b();
您可以参考此内容以澄清您的疑问。
如果您在对象上调用函数,JavaScript会将该对象视为其this / context。
例如。
let obj = {
key : 'value',
fun : function(){
}
}
// if called like obj.fun() --> obj is going to be this
// if called like let ffun = obj.fun; ffun(); ---> window/global object is going to be this
如果使用call / apply / bind调用该方法,则需要将自定义上下文指定为这些方法的第一个参数。
//if call like obj.fun.call(someObject, p1, p2)
// Or obj.fun.apply(someObject, [p1, p2])
// Or let ffun = obj.fun.bind(someObject, [p1, p2]); ffun();
// someObject is going to be this in all these 3 cases
在其他情况下,直接调用函数时,它将窗口/全局对象作为其上下文。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句