请帮忙解答 我不明白为什么上下文在定义后丢失
class A {
func() {
console.log(this)
}
}
let a = new A();
let b = a.func;
b();
最佳答案
可以引用this为了澄清你的疑问。
如果您在对象上调用一个函数,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
否则在直接调用函数的情况下,它会将窗口/全局对象作为其上下文。
关于javascript - 为什么在定义了一些从对象到变量上下文的方法后丢失了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56258912/