• ES6参考---call、apply和bind


    ES6参考---call、apply和bind

    一、总结

    一句话总结:

    bind和call与apply的区别是不会立即调用函数,常用于改变回调函数的参数,bind的参数传递方式和call一样
    <script type="text/javascript">
        function fun(age) {
            this.name = 'kobe';
            this.age = age;
            console.log('dddddddddddddd');
        }
        var obj = {};
        fun.bind(obj, 12)();
        console.log(obj);//{name: "kobe", age: 12}
        console.log(obj.name, obj.age);
    
        setTimeout(function () {
            console.log(this);//obj //{name: "kobe", age: 12}
        }.bind(obj),2000);
    
    </script>

    1、bind的参数传递和call已经apply里面的哪一个一样?

    bind的参数传递方式和call一样

    2、bind()常用的用途是什么?

    改变回调函数的this,bind是改变对象且不立即执行,为回调函数也是不立即执行

    3、bind()改变回调函数的this指向的实例?

    调用匿名函数的bind方法直接改变this:setTimeout(function () {}.bind(obj),2000);
    <script type="text/javascript">
        function fun(age) {
            this.name = 'kobe';
            this.age = age;
            console.log('dddddddddddddd');
        }
        var obj = {};
        fun.bind(obj, 12)();
        console.log(obj);//{name: "kobe", age: 12}
        console.log(obj.name, obj.age);
    
        setTimeout(function () {
            console.log(this);//obj //{name: "kobe", age: 12}
        }.bind(obj),2000);
    
    </script>

    4、Function.prototype.bind(obj)作用?

    fn.bind(obj)将函数内的this绑定为obj, 并将函数返回
    function fun(age) {
        this.name = 'kobe';
        this.age = age;
        console.log('dddddddddddddd');
    }
    var obj = {};
    fun.bind(obj, 12)();
    console.log(obj);//{name: "kobe", age: 12}
    console.log(obj.name, obj.age);

    二、call、apply和bind

    博客对应课程的视频位置:

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4   <meta charset="UTF-8">
     5   <title>05_Function扩展</title>
     6 </head>
     7 <body>
     8 <!--
     9 1. Function.prototype.bind(obj) :
    10   * 作用: 将函数内的this绑定为obj, 并将函数返回
    11 2. 面试题: 区别bind()与call()和apply()?
    12   * 都能指定函数中的this
    13   * call()/apply()是立即调用函数
    14   * bind()是将函数返回
    15 -->
    16 <script type="text/javascript">
    17     function fun(age) {
    18         this.name = 'kobe';
    19         this.age = age;
    20         console.log('dddddddddddddd');
    21     }
    22     var obj = {};
    23     fun.bind(obj, 12)();
    24     console.log(obj);//{name: "kobe", age: 12}
    25     console.log(obj.name, obj.age);
    26 
    27     setTimeout(function () {
    28         console.log(this);//obj //{name: "kobe", age: 12}
    29     }.bind(obj),2000);
    30 
    31 </script>
    32 </body>
    33 </html>

     
  • 相关阅读:
    IfcIndexedColourMap ——Example
    IfcIndexedColourMap
    IfcImageTexture
    IfcFillAreaStyleTiles
    IfcFillAreaStyleHatching
    IfcFillAreaStyle
    IfcExternallyDefinedTextFont
    IfcExternallyDefinedSurfaceStyle
    IfcExternallyDefinedHatchStyle
    IfcDraughtingPreDefinedCurveFont
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/12555252.html
Copyright © 2020-2023  润新知