Home > Web Front-end > JS Tutorial > body text

Introduction to apply and call methods

零下一度
Release: 2017-06-29 13:37:09
Original
863 people have browsed it

The methods of apply and call are exactly the same. They are both used to change the this keyword of the method and execute the method: and in strict mode and non-strict mode, the first parameter is null/undefined. The rules in both cases are the same;

bind: This method is not compatible under IE6-8 -> Similar to call and apply, they are used to change the this keyword

'use strict' //告诉当前浏览器接下来的js代码将按照严格模式进行编写var obj = {name:'张三'}function fn(num1,num2){
            console.log(num1+num2);
            console.log(this)
        }
        fn(100,200);
        //this ->window num1=100 num2=200fn.call(100,200);
        // this->100 num1 = 200 num2=undefined  NaNfn.call(obj,100,200)
        //this->obj  call在给fn传递参数的时候,是一个个传递值的,而apply不是一个个传,而是把要传递的参数值放在一个数组中进行操作。但是也相当于一个个的给fn的形参赋值fn.apply(obj,[100,200]);
        //        
         //预处理:事先把fn的this改变为我们想要的结果,并且把对应的参数值也准备好,以后要用到了,直接的执行即可。bind这里实现了预处理的效果var tempFn = fn.bind(obj,100,200);
        //只是改变了fn中的this为obj,并且给fn传递了两个参数值100和200,但此时并没有把fn这个函数执行,执行bind会有一个返回值,这个返回值tempFn就是我们把fn的this改变后的那个结果        
        tempFn();
        fn.call();
        //this->window  在严格模式下this->undefinedfn.call(null);
        //this->window 在严格模式下this->nullfn.call(undefined)
        //this->window 在严格模式下this->undefined
Copy after login

The above is the detailed content of Introduction to apply and call methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!