js中 this的指向,如果工作

<script>
function fun() {
console.log(this)
}

fun() // Window

let obj = {
a:fun
}

obj.a() // obj

function test2(c) {
c&&c()
}
test2(obj.a) // Window
// 怎么改变为指向obj?
test2(obj.a.call(obj)) // obj
test2(obj.a.bind(obj)) // obj
test2(obj.a.apply(obj)) // obj
</script>

<script>
class Test {
fun = () => {
console.log(this);
};

fun1() {
console.log(this);
}
}

let test = new Test();
test.fun(); // Test
console.log(this) // Window
test.fun.call(this); // Test 为啥不是win,原因箭头函数没有this,剪头函数的this是继承父执行上下文里面的this ,

test.fun1() // Test

test.fun1.call(this) // Window
</script>

<script>
var person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName:"John",
lastName: "Doe",
}
var person2 = {
firstName:"Mary",
lastName: "Doe",
}
console.log(person.fullName.call(person2)) // 将返回 "Mary Doe"
</script>

<script>
var x = 11;
var obb = {
x: 222,
y: {
x:333,
obc: function f() {
console.log(this)
var x = 111;
var obj = {
x: 22,
say: () => {
console.log(this.x);
}
}
obj.say()
}
}
}
obb.y.obc() // 333
</script>

js箭头函数的this指向:

https://blog.csdn.net/weixin_42519137/article/details/88053339

全面的JS this指向问题 以及如何改变this 指向的方法(call、apply、bind区别)适合初学者的一篇文章

https://blog.csdn.net/weixin_42207353/article/details/104909252

 

posted @ 2020-11-19 11:39  simple-love  阅读(117)  评论(0编辑  收藏  举报