zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    SVN服务器搭建和使用(二)
    SVN服务器搭建和使用(一)
    【CentOs】配置nginx
    【CentOs】sudo使用
    【CentOS】搭建Web服务器
    【CentOS】搭建git服务器
    【Python】内置数据类型
    【Python】Eclipse和pydev搭建Python开发环境
    【Python】一个简单的例子
    【Python】vim7.4 配置python2.6支持Gundo
  • 原文地址:https://www.cnblogs.com/wxyblog/p/14777825.html
Copyright © 2011-2022 走看看