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)
    

  • 相关阅读:
    重写trim方法时摸索出的删除数组长度的思路
    常用String类方法-Java
    Lambda入门,看这一篇幅就够了
    利用Spring AOP的通知类型以及创建通知
    SpringAOP基础
    Java开发中解决Js的跨域问题
    从properties中读取配置创建对象
    SpringBoot打包为war包,并在tomcat中运行
    查看SpringBoot应用中的嵌入式tomcat的版本
    Mybatis中返回Map
  • 原文地址:https://www.cnblogs.com/lalalagq/p/9898407.html
Copyright © 2011-2022 走看看