call and apply the difference

Explain and apply for the call, there are many online, but in order to understand it better. So here reviewed their accumulated under ~

Every function in JavaScript objects will have call and apply methods

/*apply()方法*/
function.apply(thisObj[, argArray])

/*call()方法*/
function.call(thisObj[, arg1[, arg2[, [,...argN]]]]);

definition:

apply: a call to an object method, replacing the current object with another object. For example: B.apply (A, arguments); i.e., A B object application object method.

call: calling a method of an object, replacing the current object with another object. For example: B.call (A, args1, args2); i.e. the object A calls object B Method

As can be seen from the definition, and apply both Call call a method of an object, replacing the current object with another object. The difference is that the transmission parameters, apply a maximum of only two parameters - and a new array of this object argArray, if the array will not error TypeError arg;

a plurality of call parameters can be passed, and apply the first parameter, it is used to replace the object is behind the argument list.

Basic usage:

Copy the code
function Dog(){
        this.name = "dog";
        this.showName=function(){
            console.log("这是一条"+this.name+"!")
        }
    }
    function Cat(){
        this.name="cat";
        // Dog.apply(this)
        this.showName=function(){
            console.log(this.name+" eat fish");
        }
        Dog.apply(this)
    };
    var cat = new Cat()
    // Dog.call(cat)    /*call的用法*/
    cat.showName()        /*这是一条dog*/
    console.log(cat.name)    /*dog*/
Copy the code

But if you apply different writing position, the results will also vary. As the above code

If I comment out behind apply, will apply on a open, then the execution showName () the result will be: dog eat fish 

After JS will organize more knowledge, I hope some of their precipitation ~

Guess you like

Origin www.cnblogs.com/shaozhu520/p/11299093.html