avatar
fireworks99
keep hungry keep foolish

JS this

1:this永远指向一个对象;

2:this的指向完全取决于函数调用的位置;

一、Why we need ‘this’

let bar = 1;
function getBar() {
    return bar;
}
console.log(getBar());//1

{
    let bar = 2
    let obj = {
        bar: 3,
        getBar: function () {
            return bar;//返回变量bar
        }
    }
    console.log(obj.getBar());//2
}

上面代码中obj.getBar()我想拿到obj.bar,但是拿不到。所以需要指明函数运行时所在的环境,于是就有了this。

二、’this’ refers to

  • 事件绑定
    • 静态绑定
      • 行内脚本:当前DOM节点
      • 独立脚本:全局Window对象
    • 动态绑定:当前DOM节点
    • 事件监听:全局Window对象
  • 构造函数:当前构造的实例对象
  • window定时器
    • 传函数名:全局Window对象
    • 传字符串:函数所属对象
  • call && apply:强制指定this的指向为第一个参数
  • 对象中的方法:该对象
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <!-- 1:this永远指向一个对象; -->
    <!-- 2:this的指向完全取决于函数调用的位置; -->


    <!-- 一、事件绑定 -->
    <!-- 一、事件绑定 ①. 静态绑定-->
    <!-- 一、事件绑定 ①. 静态绑定 (1).行内脚本 -->
    <input type="button" value="Button one" onclick="console.log(this)">
    <!-- output: -->
    <!-- <input type="button" value="Button one" onclick="console.log(this)"> -->

    <!-- 一、事件绑定 ①. 静态绑定 (2).独立脚本 -->
    <input type="button" value="Button two" onclick="btnClick()">

    <div id="Gold" style="background: #FFD700; height: 100px; width: 100px;"></div>

    <script>
        function btnClick() {
            console.log(this);
            //output:
            //Window {window: Window, self: Window, document: document, name: '', location: Location, …}
        }

        // 一、事件绑定 ②.动态绑定
        document.getElementById("Gold").onmouseenter = function () {
            console.log("Gold enter this: ", this);
            //output:
            //<div id="Gold" style="background: #FFD700; height: 100px; width: 100px;"></div>
        };
        // 一、事件绑定 ③.事件监听
        document.getElementById("Gold").addEventListener("mouseout", () => {
            console.log("Gold out this: ", this);
            //output:
            //Window {window: Window, self: Window, document: document, name: '', location: Location, …}
        });

        // 二、构造函数
        function Person(name, age) {
            this.name = name;
            this.age = age;
            console.log("Person this: ", this);
            //output:
            //Person {name: 'Joy', age: 24}
        }
        var p = new Person("Joy", 24);


        // 三、window定时器
        var obj = {
            setTimeoutThis: function (which = 1) {
                console.log(`setTimeout ${which} this: `, this);
            }
        }
        window.setTimeout(obj.setTimeoutThis, 1000);
        //output:
        //Window {window: Window, self: Window, document: document, name: '', location: Location, …}

        window.setTimeout("obj.setTimeoutThis(2)", 1000);
        //output:
        //{setTimeoutThis: ƒ}

        // 四、call apply 强制指定this指向
        function callAndApply(num1, num2) {
            console.log(`callAndApply ${num1 * 10 + num2} this: `, this);
        }
        callAndApply.call(p, 1, 2);
        //output:
        //callAndApply 12 this:  Person {name: 'Joy', age: 24}

        callAndApply.apply(p, [3, 4]);
        //output:
        //callAndApply 34 this:  Person {name: 'Joy', age: 24}


        // 五、对象中的方法
        let bar = 1;
        function getBar() {
            console.log("Object 1 this: ", this);
            //output:
            //Window {window: Window, self: Window, document: document, name: '', location: Location, …}
            return bar;
        }
        console.log(getBar());//1

        {
            let bar = 2
            let obj = {
                bar: 3,
                getBar: function () {
                    console.log("Object 2 this: ", this);
                    //output:
                    //{bar: 3, getBar: ƒ}
                    return this.bar;
                }
            }
            console.log(obj.getBar());//3
        }
    </script>
</body>

</html>
Site by Baole Zhao | Powered by Hexo | theme PreciousJoy