• javascript-call、apply、bind区别


    javascript-call、apply、bind区别

    this.name = "gigi";
    this.age = 22;
    var star = {
        name:"yoyo",
        age:23,
        _age:this.age,
        print(){
            console.log(this.name + " " + this.age + " " + this._age);
        }
    }
    star.print();//yoyo 23 22

    可以看到第一个this指向的都是star对象,star对象里_age指向的this是全局

    call()、apply()、bind() 都是用来重定义 this 这个对象的

    star.print.call(this);//gigi 22 undefined
    star.print.apply(this);//gigi 22 undefined
    star.print.bind(this)();gigi 22 undefined
    

     可以看到this指向都指向全局了全局没有_age属性,故打印出undefined,bind 返回的是一个新的函数,你必须调用它才会被执行,故得在后面加多个()

    对比call 、bind 、 apply 传参情况下

    var person1 = {
        name:"行运茶",
        print:function(arg1,arg2){
            console.log("My name is " + this.name + arg1 + arg2);
        }
    }
    
    var person2 = {
        name:"快乐水",
        print:function(arg1,arg2){
            console.log("My name is " + this.name + arg1 + arg2);
        }
    }
    person1.print.call(person2,"好","帅");//My name is 快乐水好帅
    person1.print.apply(person2,["好","帅"]);//My name is 快乐水好帅
    person1.print.bind(person2,"好","帅")();//My name is 快乐水好帅

    call 、bind 、 apply 这三个函数的第一个参数都是 this 的指向对象,第二个参数就不一样,call和apply是一样的,直接接放进去的,第二第三第 n 个参数全都用逗号分隔

    apply 的所有参数都必须放在一个数组里面传进去 

  • 相关阅读:
    刚开发的游戏《天黑请闭眼》
    用手机控制服务器
    专业网站打包/解包asp工具(E文精装版本)!
    令我爱慕的女子(转自7di.net)
    8088 汇编速查手册
    Asp调用函数是否会影响性能?
    文档管理器
    ubuntu install xxx.deb
    Java线程池的原理及几类线程池的介绍
    ubuntu download file path
  • 原文地址:https://www.cnblogs.com/kootimloe/p/13330501.html
Copyright © 2020-2023  润新知