④ this

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

但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。

在方法中,this 表示该方法所属的对象。
如果单独使用,this 表示全局对象。
在函数中,this 表示全局对象。
在函数中,在严格模式下,this 是未定义的(undefined)。
在事件中,this 表示接收事件的元素。
类似 call() 和 apply() 方法可以将 this 引用到任何对象。
函数内部的 this 指向谁,取决于函数的调用方式
谁调用函数 函数内部的this 就是谁

 function box() {
            // 严格模式下  全局函数内部的this 是 undefined
            console.log(this); //window
        }
        var a = 1;
        console.log(window.a);
        console.log(window.box);
        box()
        // window.box()

        //2-全局作用域中使用 this  也是window
        console.log(this);

        // 3-匿名函数 延时器 定时器 
        // setInterval(function () {
        //     console.log(this); //window
        // }, 1000);


        // *****this的正常使用场景 
        function Dog(name, age) {
            // new Dog  构造函数内部 默认会创建一个 this 
            // var this = {};
            console.log(this); //

            // 增加了属性
            this.name = name;
            this['age'] = age;
            // 增加了方法
            this.bark = function () {
                console.log('汪汪')
                //  对象方法内部的this  
                console.log(this);
            }
            return this;
        }
        let d1 = new Dog('小黑', 1)
        let d2 = new Dog('小白', 1)
        console.log(d1);
        console.log(d2);

        //  对象方法内部的this 
        d1.bark()
        d2.bark()

        let ipt = document.querySelector('#ipt')
        ipt.onchange = function () {
            console.log(this); //ipt  输入框本身
        };
        var a = 1;
        
        function aa() {};

        // 立即执行函数 
        // function fn(){
        //     console.log(this);
        // }
        // fn();

        ;
        (function () {
            console.log(this);
        })();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值