美文网首页
call(), apply(), bind() - javasc

call(), apply(), bind() - javasc

作者: Zihowe | 来源:发表于2017-08-27 04:56 被阅读12次

    bind()
    会绑定一个对象,让其成为this。最后返回一个新的函数拷贝。

    function currying
    creating a copy of a function but with some preset parameters.
    如果额外传递参数给bind(),那个这个参数就会成为permanent的值,再使用这个新的函数拷贝时,就不用再传那个参数了,因为已经绑定好了。

    cal()
    会直接传递一个对象成为this, 然后执行方程。

    apply()
    和call的区别在于,传递参数时,用的是一个数组。

    var person = {
        firstname: 'John',
        lastname: 'Doe',
        getFullName: function() {
            
            var fullname = this.firstname + ' ' + this.lastname;
            return fullname;
            
        }
    }
    
    var logName = function(lang1, lang2) {
    
        console.log('Logged: ' + this.getFullName());
        console.log('Arguments: ' + lang1 + ' ' + lang2);
        console.log('-----------');
        
    }
    
    var logPersonName = logName.bind(person);
    logPersonName('en');
    
    logName.call(person, 'en', 'es');
    logName.apply(person, ['en', 'es']);
    
    (function(lang1, lang2) {
    
        console.log('Logged: ' + this.getFullName());
        console.log('Arguments: ' + lang1 + ' ' + lang2);
        console.log('-----------');
        
    }).apply(person, ['es', 'en']);
    
    // function borrowing
    var person2 = {
        firstname: 'Jane',
        lastname: 'Doe'
    }
    
    console.log(person.getFullName.apply(person2));
    
    // function currying
    function multiply(a, b) {
        return a*b;   
    }
    
    var multipleByTwo = multiply.bind(this, 2);
    console.log(multipleByTwo(4));
    
    var multipleByThree = multiply.bind(this, 3);
    console.log(multipleByThree(4));
    

    相关文章

      网友评论

          本文标题:call(), apply(), bind() - javasc

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