JavaScript - 理解this关键字(面试常问)

158 阅读1分钟

this关键字

  先来看一段菜鸟教程的定义:

面向对象语言中 this 表示当前对象的一个引用。

  • 在方法中,this 表示该方法所属的对象。

  • 如果单独使用,this 表示全局对象。(Window对象)

  • 在函数中,this 表示全局对象。(Window对象)

  • 在函数中,在严格模式下,this 是未定义的(undefined)。

  • 在事件中,this 表示接收事件的元素。

  • 类似 call() 和 apply() 方法可以将 this 引用到任何对象。

this的使用

  来看一些有关this的题目

        var age = 50;
        let obj = {
            age: 20,
            sayHi() {
                console.log(this.age);
                return function() {
                    console.log(this.age);
                }
            }
        }
        let ace = {
            age:30
        }
        
        ace.sayHi = obj.sayHi;
        ace.sayHi(); // 30 this=ace
        var sayHi = ace.sayHi;
        sayHi(); // 50

        // 下面的代码可以拆分为 var fn = obj.sayHi();fn();
        obj.sayHi()(); // 20 50

  下面的例子可以通过call方法借用数组的方法

        arr1 = {
            length: 0,
            // push(val) {
            //     this[this.length++] = val;
            // },
            // forEach(fn) {
            //     for(let i=0;i<this.length;i++){
            //         fn(this[i], i);
            //     }
            // },
            push(val) {
                Array.prototype.push.call(this, val);
            },
            forEach(fn) {
                Array.prototype.forEach.call(this, fn);
            }
        }

        arr1.push("aaa");
        arr1.push("bbb");

        arr1.forEach(r => {
            console.log(r);
        })