this 指向

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 <script>
        // apple()
        var o = {
            name: 'andy'
        };

        function fn(arr) {
            console.log(this);
            // console.log(arr); // pink  
        }
        // fn.apply();   // Window 
        // 1 调用函数  2 可以改变this 指向   
        // 3 但是他的参数必须是数组(伪数组)
        // fn.apply(o); //{name: "andy"}
        // fn.apply(o, ['pink']); 
        // apply 的主要应用 借助于数学内置对象求最大值
        // Math.max(); 
        var arr = [1, 66, 3, 99, 4];
        // null 表示 不需要 改变this指向
        // var max = Math.max.apply(null, arr);
        var max = Math.max.apply(Math, arr);
        var min = Math.min.apply(Math, arr);
        console.log(max); // 99
        console.log(min); // 1
    </script>
 
 

 

 

  <button>按钮点击</button>
    <script>
        // apple()
        var o = {
            name: 'andy'
        };

        function fn(a, b) {
            console.log(this);
            console.log(a + b); // 3

        }
        var f = fn.bind(o, 1, 2);
        f();

        // 1 不会调用原来的函数  可以改变原来函数内部的this 指向
        // 2 返回的是原函数改变 this之后产生的新函数
        // 3 如果有的函数不需要立即调用 但是又想改变这个函数内部的 this 指向此时 用bind
        // 案例需求  4 有一个按钮 当点击了之后 就禁用这个按钮,3秒后 开启这个按钮
        var btn = document.querySelector('button');
        btn.addEventListener('click', function() {
            this.disabled = true;
            setTimeout(function() {
                this.disabled = false;
            }.bind(this), 3000); // 这个this 指向的是 btn 这个对象
        })
    </script>
 
 

 

posted @ 2020-06-08 19:42  EricBlog  阅读(113)  评论(0编辑  收藏  举报