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)
    

  • 相关阅读:
    MyEclipse中的Tomcat跑大项目时内存溢出:permgen space
    MyEclipse新建工作空间后的配置详细步骤
    解决eclipse复制粘贴js代码卡死的问题
    eclipse复制工作空间配置
    maven项目检出后报错(包括编译报错和运行报错)的常见检查处理方式
    MyEclipse中引用的maven配置文件只访问私服的配置
    图标网站
    afasf
    一个权限管理模块的设计(转载)
    奇艺下载
  • 原文地址:https://www.cnblogs.com/lalalagq/p/9898407.html
Copyright © 2011-2022 走看看