call, appply , bind

call

1.call从何而来?

每个javascript函数其实都是Function对象 , 而Function对象是构造函数 , 构造函数是有原型对象的Function.prototype

 

 call就是在原型对象属性里面来的 , call作为一种属性 , 也是一种方法.

2.call如何用?

函数调用call方法 , 将this绑定在对象上

栗子:

     function person(){
            console.log(this.name)
        }
        var egg = {
            name:'丹丹'
        }
        person.call(egg)  //'丹丹'

相当于

        var egg = {
            name:'丹丹',
            function person(){
                console.log(this.name) //this的隐式绑定: 当person引用有上下文对象时 , 就会把函数person调用中的this绑定到这个对象egg了
            }
        }
     e
gg.person() //'丹丹'
egg是真正的调用位置, 因此this指向了egg

 

修改  this === 修改  egg

function person (age,sex){
    this.age = age;
    console.log(this.name,this.age,sex,egg, 829)  //丹丹 18 女 {name: "丹丹", age: 18} 829
}
var egg = {
    name:'丹丹'
}
person.call(egg,18,'女') 

 

appply

与call区别在于 apply 传入参数为数组

function person (age,sex){
    this.age = age
    console.log(this.name,this.age,sex,egg, 829)  //丹丹 18 女 {name: "丹丹", age: 18} 829
}
var egg = {
     name:'丹丹'
}
person.apply(egg,[18,'女']) 

 

bind

绑定this ,

与call和的区别 :  但函数不执行 , 需要将函数赋值给变量

用法

function person (age,sex){
   this.age = age
   console.log(egg,sex,age,this.name,829)  //{name: "丹丹", age: 18} "女" 18 "丹丹" 829      
}
let foo = person.bind(egg,18,'女')
foo()

必须赋值给变量 , 要不要函数内部的this还是会执行window

 

posted @ 2021-07-09 11:20  混名汪小星  阅读(87)  评论(0编辑  收藏  举报