• bind,apply,call的区别


    在Javascript中,bind, apply, call方法都可以显式绑定上下文this,这三者有何不同呢?


    bind只绑定this不马上执行

    var person = {
        firstname: 'darren',
        lastname: 'ji',
        getFullName: function(){
            var fullname = this.firstname + ' ' + this.lastname;
            return fullname;
        }
    };
    
    //在浏览器中这里的this就是指向window
    var logName = function(arg1, arg2){
        console.log(this.getFullName());
    }
    
    //bind只是设置了this的指向,本身并不能执行
    var logPersonName = logName.bind(person);
    
    //darren ji
    logPersonName();


    call不仅绑定this,还马上执行,并接受可变参数

    var person = {
        firstname: 'darren',
        lastname: 'ji',
        getFullName: function(){
            var fullname = this.firstname + ' ' + this.lastname;
            return fullname;
        }
    };
    
    //在浏览器中这里的this就是指向window
    var logName = function(arg1, arg2){
        console.log(this.getFullName());
        console.log('Arguments: ' + arg1 + ' ' + arg2);
    }
    
    //darren ji
    //Arguments: en es
    logName.call(person, 'en','es');

    apply不仅绑定this,也马上执行,并接受数组

    var person = {
        firstname: 'darren',
        lastname: 'ji',
        getFullName: function(){
            var fullname = this.firstname + ' ' + this.lastname;
            return fullname;
        }
    };
    
    //在浏览器中这里的this就是指向window
    var logName = function(arg1, arg2){
        console.log(this.getFullName());
        console.log('Arguments: ' + arg1 + ' ' + arg2);
    }
    
    //darren ji
    //Arguments: en es
    logName.apply(person, ['en', 'es']);
  • 相关阅读:
    nginx 禁止访问某个目录
    ssh 无法链接的解决思路
    linux 时间修改(同步到时间服务器)
    BitNami Gitlab的重启问题
    gitlab push时报错
    VirtualBox 安装centos后无法上网
    VirtualBox 创建64位系统的问题
    NOIP2010 题解
    NOIP2011 题解
    NOIP2012 题解
  • 原文地址:https://www.cnblogs.com/darrenji/p/5002852.html
Copyright © 2020-2023  润新知