export class Http {
m1(s:string) {
console.log("in m1",s);
}
m2(s:string) {
console.log("in m2",s);
}
}
export class a{
http=new Http();
op(s:string) {
console.log(this);
this.http.m1(s+"from a");
}
}
export class b {
http=new Http();
constructor() { }
op1(s:string) {
console.log(this);
this.http.m2(s+"from b");
}
}
//main function call
let v = 2
let ptr = null;
let a1 = new a();
let b1 = new b();
switch(v) {
case 1:
ptr=a1.op;
break;
case 2:
ptr=b1.op1;
break;
}
ptr("s");
在上面的示例中,我创建了一个&; b类具有op&; op1法。 根据我的选择(比如在switch语句中),我想调用一个方法。 但我得到一个错误“无法读取Undefined的属性”http“。 有人能解释一下为什么会发生这种情况吗?
提前感谢!!
这是因为执行ptr=a1.op; ptr(“s”);
与执行a1.ptr(“s”);
有根本不同
此
值取决于调用函数的位置。 如果您调用ptr(“s”)
,则它相当于window.ptr(“s”)
,因此this
是slappy模式下的window
,严格模式下的undefined
(有关严格模式和slappy模式的详细信息,请阅读MDN文档)
当您从对象调用函数时,this
是对象这就是a1.op(“s”)
将工作的原因,因为this
将是a1