29、js中this指向

发布于:2024-07-20 ⋅ 阅读:(156) ⋅ 点赞:(0)

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);


网站公告

今日签到

点亮在社区的每一天
去签到