call、apply、bind 三种方法的用法和区别

1、call、apply、bind三个方法都有两个参数;第一个参数都是this(对象);

2、call和apply都是立即执行函数,不必调用。call第二个参数不用数组接收,apply用数组接收,类型可以是任意类型

1)

function a(b){

console.log('a'+this.bb+b)

}

let b={bb:"b"};

    a.call(b,"第二个参数");//冒充b對象


1

2)

console.log(result(1));

function a(){ console.log(this,'a')};

function b(){console.log()}

a.call(b,'我是B的参数')


this指向b(a函数执行了)

再次修改第二种写法:

function a(){ console.log(this+'执行了a')};

function b(){console.log(this+"执行了b")}

a.call.call(b)


this指向window,指行了b

总结:

一个函数call2次或者2次以上 执行的永远是b(b需要是一个函数),参数会直接输出

3、bind返回值是一个函数(不会立即执行,需要调用),传参和call一样


应用

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title></title>

</head>

<body>

<div id="app">

    <p v-for="count in 10">第{{count}}次, 总计 10次</p>

    <ul ref="ulParent">

        <li style="height: 60px;">1</li>

        <li style="height: 30px;">2</li>

        <li style="height: 50px;">3</li>

        <li style="height: 160px;">4</li>

        <li style="height: 10px;">5</li>

    </ul>

    <button @click="getAllLiHeight()">获取高度数组</button>

    <button @click="dealSome()">验证some</button>

</div>

<script src="lib/vue.js"></script>

<script>

    new Vue({

        el:'#app',

        data: {

          dataArr: ['撩课', 'itlike11.com', '哈哈哈哈']

        },

        methods: {

            getAllLiHeight(){

                let liHeightArr = [];

                // 1. 获取dom元素

                let allLis = this.$refs.ulParent.getElementsByTagName('li');

                console.log(allLis[0]);

                console.log(Array.prototype.slice.call(allLis));

                Array.prototype.slice.call(allLis).forEach(li => {

                    liHeightArr.push(li.clientHeight);

                });

                console.log(liHeightArr);

            },

            dealSome(){

                let result = this.dataArr.some((str)=>{

                    return str === 'itlike.com';

                });

                console.log(result);

            }

        }

    });

    var obj1 = {0:'hello',1:'world'};

    var obj2 = {0:'hello',1:'world',length:2};

    var obj3 = [1,2];

    var obj4 = "string";

console.log(Array.prototype.slice.call(obj4,1));//第二个参数相当于截取得起始下标

//Array.prototype.slice  调用Array类中的饿原型方法

//Array.prototype.slice.call(res)//使用call冒充一个据有length对象,转换成数组,绑定this指向——>对象.slice() 或者  字符.slice() 或者  数组.slice() ——>第二个参数为截取的起始下标

//作用:将传入具有length属性的参数转为数组 

</script>

</body>

</html>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容