zoukankan      html  css  js  c++  java
  • call,apply,bind

    call

    非严格模式

            var obj = { name: "jie" };
            function fn(num1, num2) {
                console.log(this);
                console.log(num1 + num2);
            }
            fn(100,200);   //this ->window  num1=100,num2=200
            fn.call(100,200)   //this->100  num1 = 200,num2=undefined
            fn.call(obj,100,200);  //this->obj  num1 = 100,num2=200
    
            fn.call();  //this->window
            fn.call(null); //this->window
            fn.call(undefined); //this->window
    
    

    严格模式

            'use strict';
            var obj = {name:"jie"};
            function fn(num1,num2){
                console.log(this);
                console.log(num1+num2);
            }
            fn(100,200);   //this ->window  num1=100,num2=200
            fn.call(100,200)   //this->100  num1 = 200,num2=undefined
            fn.call(obj,100,200);  //this->obj  num1 = 100,num2=200
    
            fn.call();   //undefined
            fn.call(null);  //null
            fn.call(undefined);  //undefined
    

    apply

    1. apply和call的方法的作用是一模一样的,
    2. call在给fn传递参数的时候,是一个个的传递值的,而apply不是一个一个传,而是把要给fn传递的参数值统一放在一个数组中进行操作,但是也相当于一个个的给fn的形参赋值
            var obj = { name: "jie" };
            function fn(num1, num2) {
                console.log(this);
                console.log(num1 + num2);
            }
            fn(100,200);   //this ->window  num1=100,num2=200
            fn.apply([100,200])   //this->[100,200]  num1 = NaN,num2=NaN
            fn.apply(obj,[100,200]);  //this->obj  num1 = 100,num2=200
    
            fn.apply();  //this->window
            fn.apply(null); //this->window
            fn.apply(undefined); //this->window
    

    bind

    1. 预处理:事先把fn的this改变为我们想要的结果,并且把对应的参数值也准备好,以后要用到了,直接的执行即可
    2. var result = fn.bind(obj,1,2) 只是改变了fn中的this为obj,并且给fn传递了两个参数值100,200,但是此时并没有把fn这个函数执行,执行bind会有一个返回值,这个返回值result就是我们把fn的this改变后的哪个结果
            var obj = { name: "jie" };
            function fn(num1, num2) {
                console.log(this);
                console.log(num1 + num2);
            }
            var result = fn.bind(obj, 100, 200);  //this->obj  num1 = 100,num2=200
            console.log(result)
    

  • 相关阅读:
    单例模式
    自旋锁与互斥锁
    CAS无锁机制原理
    乐观锁和悲观锁
    读写锁
    Java锁机制-重入锁
    原 Linux搭建SVN 服务器2
    原 Linux搭建SVN 服务器
    Sublime Text 3 破解版 + 注册机 + 汉化包 + 教程
    Sublime Text 3 常用插件以及安装方法(转)
  • 原文地址:https://www.cnblogs.com/lalalagq/p/9898407.html
Copyright © 2011-2022 走看看