欢迎光临
我们一直在努力

typescript-函数this指向

这里讲的东西比较绕,大家多看几遍。

先上代码吧

function a() {
console.log("我的名字是:", this.name);
}
let obj = { name: "zsf" };
a();
a.call(obj);
a.apply(obj);
a.bind(obj)();

function b(arg1, arg2) {
console.log("我的名字是:", this.name);
console.log("我的参数是:", arg1, arg2);
}
b("参数1", "参数2");
b.call(obj, "call参数1", "call参数2");
b.apply(obj, ["apply参数1", "apply参数2"]);
b.bind(obj)("bind参数1", "bind参数2");

function c(…args: any[]) {
console.log("我的名字是:", this.name);
console.log("我的参数是:", args.length);
}
c("参数1", "参数2");
c.call(obj, "call参数1", "call参数2");
c.apply(obj, ["apply参数1", "apply参数2"]);
c.bind(obj)("bind参数1", "bind参数2");

let obj1 = {
name: "obj1的name",
func: () => {
console.log("我的名字:", this);
},
innerObj: {
name: "innerObj的name",
innerFunc: function () {
console.log(this.name);
},
},
func2() {
console.log(this.name);
},
func3() {
this.value = "func3的value";
function func3Inner() {
this.value = "func3Inner的value";
const func = () => {
console.log("—" + this.value);
};
func();
}
func3Inner();
},
};

let obj2 = { name: "obj2的名字" };
obj1.func();
obj1.innerObj.innerFunc();
obj1.innerObj.innerFunc.call(obj2);
obj1.func2();
obj1.func2.call(obj2);
obj1.func3();

tsc index.ts

在浏览器里看下控制台输出:

大家以上的代码一层层看,这里我给下总结啊:

普通函数:

  • 可以通过call,apply,bind来更改this的指向
  • call,apply更改指向的时候,直接调用了函数;bind更改指向的时候,返回了一个函数,需要手动再次调用一下。
  • call更改指向需要传参的时候是参数一个个传递过去的,apply更改指向需要传参的时候是把参数传到了一个参数数组中的。
  •      4. 普通函数的this指向的是调用的时候的对象。而箭头函数this指向的是上一层最近的普通函数不能动态的更改this的指向。

    赞(0)
    未经允许不得转载:171主机测评 » typescript-函数this指向
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址