变幻莫测的this指向

1、事件调用环境

谁触发事件,函数里面的this指向的就是谁。

.box{
    width: 100px;
    height: 100px;
    background: #0a8cd2;
    position: relative;
    left: 0px;
    transition: 1s;
}
.lili{
    width: 100px;
    height: 100px;
    background: #0a8cd2;
    position: relative;
    left: 0px;
    transition: 1s;
}

<div class="box"></div>
<div class="lili"></div>

let box  = document.querySelector('.box');
let lili  = document.querySelector('.lili');
box.onclick = move;
lili.onclick = move;
function move() {
    this.style.left = '100px';
}

2、全局环境

  • 浏览器环境: this指向window
  • node环境: this 指向module.exports

3、函数内部

this指向函数的的调用对象

function func() {
    console.log(this);
}
func();  // window (严格模式:undefined)
window.func(); // window
let obj = {
    a: 10,
    b: function(){
        console.log(this);
    }
}
obj.b(); // this === obj
let fun = obj.b;
fun(); // window

4、构造函数

构造函数中的this指向的是实例对象。

// 构造函数
function Fun() {
    this.num = 10;
    console.log(this);
}
let obj = new Fun();
console.log(obj.num);    // 10

new运算符的作用
如果构造函数中有return

5、箭头函数

箭头函数中this指向定义处上一层作用域的this。

// 箭头函数
let obj3 = {
    fun: () => {
        console.log(this);
    }
}
obj3.fun();  // window

6、修改this指向

call、apply和bind的第一个参数指定了函数的this指向。(箭头函数的this指向不可被修改。)

let person = {
    fullname: "xiaohua"
}
let obj4 = {
    fun1: function() {
        console.log(this.fullname);
    },
    fun2: () => {
        console.log(this.fullname);
    }
}
obj4.fun1.call(person); // xiaohua
obj4.fun2.call(person); //undefined
obj4.fun1.bind(person)(); //xiaohua
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 事件调用环境: 谁触发事件,函数中的this指向就是谁 全局环境: 全局环境下this指向的window 如果j...
    Marting424阅读 1,355评论 0 0
  • 写在前面 知识就是力量。 ——安琪拉知识就是力量,但更重要的是运用知识的技能。 —— 培根本文主要介绍了JavaS...
    捡代码的小女孩阅读 1,711评论 0 0
  • JS--this指向问题 1.function中的this在不同环境下的指向 事件调用环境:谁触发的事件,函数里面...
    不秃头的赖阅读 2,563评论 0 1
  • (1)事件调用环境:谁触发事件,函数里面的this指向就是谁(某个DOM)。 (2)node全局环境:this指向...
    温室寻荒凉阅读 1,837评论 0 0
  • 不同环境下 function 的 this 的不同指向 事件调用环境 - 谁触发事件,函数里面的 this 就指向...
    direwolf_阅读 2,910评论 0 0

友情链接更多精彩内容