this指向简述

1. 作为对象的属性被调用

this指向对象

let object = {
    name: 'my name',
    test: function() {
        console.log(this.name);
    }
}
object.test(); // my name

2. 作为普通函数被调用

this总是指向全局对象(浏览器中通常为window);严格模式下,this指向undefined。

// 非严格模式下
let test = function() {
    console.log(this); // window
}
test();

// 严格模式下,函数中使用 ES5 的 'use strict'。
let test = function() {
    'use strict'
    console.log(this); // undefined
}
test();

 3. 箭头函数

箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this,即 this 和父级作用域志向相同。

let object = {
    test() {
        setTimeout(function() {
            setTimeout(function() {
                console.log(this); // window
            })
            setTimeout(() => {
                console.log(this); // window
            })
        })
        setTimeout(() => {
            setTimeout(function() {
                console.log(this); // window
            })
            setTimeout(() => {
                console.log(this); // test
            })
        })
    }
}
object.test();

 4. 作为构造器调用

通常情况下,this指向被构造函数返回的实例;

例外:如果构造函数显式的返回了一个Object类型的对象,那么结果也会只得到这个对象。

let Test = function(name) {
    this.name = name;
    console.log(this);
}
let test1 = new Test('张三'); // Test { name: '张三' }
let test2 = new Test('李四'); // Test { name: '李四' }

 5. 当一个DOM元素被绑定事件处理函数时,this指向被点击的这个元素

6.  call 和 apply 调用

  • 作用:动态改变 this 指向,使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数;
  • 本质:允许为不同的对象分配和调用属于一个对象的函数或方法;
  • 区别:
  1. call(this, params1, params2, ...)
  2. apply(this, [params1, params2, ...])

可参考链接:call 和apply的作用与区别

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值