首页 > 其他分享 >call,apply,bind修改函数内部this指向

call,apply,bind修改函数内部this指向

时间:2023-01-28 11:57:06浏览次数:40  
标签:指向 bind call 按钮 var apply

1.call的应用,(立即调用)

// // 1.call改变函数内部this指向的运用
            var o={
                name:"andy",
                age:12,
            }
            function fn(num1,num2){
                console.log(this)
                console.log(num1+num2)
            }
            fn.call(o,1,3)

2.apply的应用(立即调用)

// 2.apply改变函数内部this指向的运用,传递参数必须是数组
            var arr=[2,6,7,5,77,4]
            var max=Math.max.apply(Math,arr)
            var min=Math.min.apply(Math,arr)
            console.log(max)
            console.log(min)

3.bind的应用(不会立即调用),常用于定时器

        <button>按钮三秒后开启</button>
<script>
var btn1 = document.querySelector('button');
            btn1.onclick = function() {
                this.disabled = true; //这个this指向的是btn这个按钮,disabled为true即为不可用状态
                setTimeout(function() {
                    this.disabled = false; //定时器函数里面的this指向的是window
                }.bind(this), 3000); //bind改变this的指向,这个this指向的是btn这个对象
            }
</script>

 

<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<script>
var btn1 = document.querySelectorAll('button');
            for(var i=0;i<btn1.length;i++){
                btn1[i].onclick=function(){
                    this.disabled=true
                    setTimeout(function(){
                        this.disabled=false
                    }.bind(this),2000)
                }
            }
</script>

 

标签:指向,bind,call,按钮,var,apply
From: https://www.cnblogs.com/hs20011205/p/17069873.html

相关文章