zoukankan      html  css  js  c++  java
  • this的指向

    // 这里是全局中的 this 是指向 window 的
            console.log(this);
    
            var a = 10;
            // 可以直接使用 window.a 输出的结果为10
            console.log(this.a);
    
            function box1() {
                //            this 是指向 window 的
                console.log(this);
    
                function box2() {
                    //            this 是指向 window 的
                    console.log(this);
    
                    function box3() {
                        //            this 是指向 window 的
                        console.log(this);
                    }
                    // 这里相当于是window去调用的
                    box3();
                }
                // 这里相当于是window去调用的
                box2();
            }
            // 这里相当于是window去调用的
            box1();
    
            // 在点击事件中, this 指向的是当前触发事件的元素对象
            document.body.onclick = function() {
                // 指向的是 body 对象
                console.log(this);
            }
    
            document.querySelector('.box1').onclick = function(e) {
                // this 执行结果,为 div.box1 对象 
                console.log(this);
                // 阻止消息冒泡,不然上面的body 会输出
                e.stopImmediatePropagation();
    
            }
    
            $('div').click(function() {
                // 会输出当前被点击的 div 对象
                console.log(this);
            })
    
            // 在构造函数中,this 表示的是正在初始化的对象本身
            function Base(name) {
                // this 指的是当前在创建的对象
                console.log(this);
                this.name = name;
                console.log(this);
            }
            var ba = new Base('小明');
    
            var obj = {
                name: '小强',
                age: 20,
                run: function() {
                    // 这里 this 是 window (主要是看谁来调用的这个方法)
                    console.log(this);
                }
            }
            var fun = obj.run;
            fun();
  • 相关阅读:
    crossvcl使用
    CSS垂直居中的方法
    IIS7 启用GZip压缩
    javascript arguments解释,实现可变长参数。
    DataTable转List<dynamic>
    Bootstrap表单
    Func<T>、Action<T> 的区别于说明
    jQuery.fn.extend() 与 jQuery.extend()
    javascript this关键字指向详解
    javascript call与apply关键字的作用
  • 原文地址:https://www.cnblogs.com/zbly/p/10045710.html
Copyright © 2011-2022 走看看