29、js中this指向

this就是一个使用在作用域内的关键字

1.普通函数调用——》指向window

function fn(){
    console.log(this)    //Window
}
fn()

2.对象调用——》指向对象名

  var obj = {
        a: fn,
  };
  console.log(obj.a());

3.定时器函数调用——》指向window

setTimeout(function () {
     console.log(this);
}, 1000);

4.事件处理函数调用——》指向事件源

 document.onclick = function () {
      console.log(this);
 };

5.箭头函数调用——》指向父级作用域

           document.onclick = function () {
                console.log(this);
                var th = function () {
                    console.log("this2", this);
                };
                th();
            };

6.构造函数调用——》指向实例对象

           function CreatObject(name, age) {
                this.name = name;
                this.age = age;
                console.log(this, this.name);
            }
            const o1 = new CreatObject();
            console.log(o1);

改变this指向

1.call(this新指向,参数1,参数2,参数3,,,)

立即执行

2.appply(this新指向,[参数1,参数2,,,])

立即执行

3.bind(this新指向,参数1,参数2,参数3)

不立即执行

         // function fn(a, b) {
            //     console.log(this);
            //     console.log(a, b);
            // }
            // fn();
            // //this指向改为document
            // fn.call(document, 10, 20);

            // function fn(a, b) {
            //     console.log(this);
            //     console.log(a, b);
            // }
            // fn(10, 20);
            // fn.apply(document, [10, 20]);


            function fn(a, b) {
                console.log(this);
                console.log(a, b);
            }
            var obj = {
                username: "tom",
            };
            document.onclick = fn.bind(obj);
            setTimeout(fn.bind(obj, 1, 3), 1000);

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值