这里讲的东西比较绕,大家多看几遍。
先上代码吧
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
在浏览器里看下控制台输出:

大家以上的代码一层层看,这里我给下总结啊:
普通函数:
4. 普通函数的this指向的是调用的时候的对象。而箭头函数this指向的是上一层最近的普通函数,不能动态的更改this的指向。

