• call,apply,bind的用法及区别


    <script>

    function test(){
    console.log(this)
    }
    // new test();
    //函数调用call方法的时候,就会执行。
    //call的参数:第一个参数:方法执行的时候,方法中的this的指向。第二个参数:表示方法执行所需要的实际参数。
    var obj ={ name:"zhagafd"};
    // test.call(obj,"hello");
    //applly的参数:第一个参数:方法执行的时候,方法中this的指向。第二个参数:方法执行的时候,所有形参的一个数组[];
    test.apply(obj,["hello"]);
    //bind方法的特点:绑定方法执行时的this,并没有马上执行,而是返回一个方法对象
    //bind方法传实际参数的方法与call一致
    var foo = test.bind(obj,"hello");
    foo();
     
    //继承
    function person(name,age){
    this.name = name;
    this.age = age;
    this.eat = function(){
    console.log('eating...');
    }
    this.show = function(){
    console.log(name+''+age);
    }
    }
    //定义一个student类,继承person
    function stundent(name,age,score){
    this.score = score;
    person.call(this,name,age);
    }
    //实例化student
    var stu = new stundent('tom',18,88);
    stu.eat();
    stu.show();
     
    //回调函数的this指向指定后,并没有马上去执行,所以当需要指定回调函数的this时,使用bind方法来实现
    var obj = {name:"zhangsan"};
    setTimeout(function(){
    console.log(this);
    }.bind(obj),100)
    </script>
  • 相关阅读:
    Python"sorted()"和".sort()"的区别
    pandas.DataFrame.sample
    List和Tuple的中的method对比
    Python格式输出汇总
    Ubuntu12.04安装配置vncserver
    Ubuntu12.04安装配置x11vnc
    Python的list中的选取范围
    Python中使用"subplot"在一张画布上显示多张图
    pylab和pyplot的区别
    c++下new与delete基础用法
  • 原文地址:https://www.cnblogs.com/wtdall/p/12077758.html
Copyright © 2020-2023  润新知