美文网首页
JS:call、apply和bind的用法及区别

JS:call、apply和bind的用法及区别

作者: kiwi_leo | 来源:发表于2019-05-31 00:47 被阅读0次

    一、call和apply

    1、call和apply都是function.prototype的方法,每一个方法的对象实例 new function() 都会有这两个属性;

    2、这两个属性都是针对方法的属性针对方法使用

    3、call和apply使用方法相同;

    4、call和apply的参数不同;
    (1)test.call ( this, param1 , param2 , param3 ) ; // 可以传多个参数
    (2)test.apply ( this, paramArray ) ; // 只能传两个参数,第二个一般为数组

    二、bind

    call和apply会改变this指向,然后执行函数;
    bind会改变this指向后,返回一个绑定新this的函数;

    三、demo

    var name = "aven";
    var age = 18;
    
    var obj = {
          name: "ake",
          age: this.age,
          test: function(){
              console.log("name: ", this.name, "age: ", this.age );
      }
    };
    
    obj.test(); 
    // name: ake  age: undefined
    // 因为obj.test() 只会调用本身属性,本身没有age属性,但是有name属性
    
    obj.test.call()
    // name:  aven age:  18
    // call参数为null或undefined时默认指向window,
    // this含有属性 name : "aven", age: 18,所以输出结果变化
    
    var name = "testName";
    var age = 18;
    
    var obj = {
          name: "ake",
          age: this.age,
          test: function(gender, home){
              console.log("name: ",this.name,"age:",this.age,"gender:",gender,"home: ", home);
      }
    };
    
    var person = {
          name: "aven",
          age: 18
    }
    
    obj.test.call(person, "female", "China")  // name:  aven age: 18 gender: female home:  China
    obj.test.apply(person, ["female", "China"])  // name:  aven age: 18 gender: female home:  China
    obj.test.bind(person, "female", "China")()  // name:  aven age: 18 gender: female home:  China
    obj.test.bind(person, ["female", "China"])()  // name:  aven age: 18 gender: ["female", "China"] home:  undefined
    
    obj.test.bind(this, "female", "China")() // name:  testName age: 18 gender: female home:  China
    

    相关文章

      网友评论

          本文标题:JS:call、apply和bind的用法及区别

          本文链接:https://www.haomeiwen.com/subject/fahitctx.html