Monday 14 August 2017

JavaScript Function Apply

The JavaScript apply() Method

The apply() method is similar to the call() method:

Example

var person = {
    firstName:"John",
    lastName: "Doe",
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var myObject = {
    firstName:"Mary",
    lastName: "Doe",
}
person.fullName.apply(myObject);  // Will return "Mary Doe"


 The Difference Between call() and apply()

The only difference is:
call() takes any function arguments separately.
apply() takes any function arguments as an array.
The apply() method is very handy if you want to use an array instead of an argument list.
If you want to obtain the largest number in a list of numbers you can use the Math.max() method:

Example

Math.max(1,2,3);  // Will return 3
Since JavaScript arrays do not have a max() method, you can apply the Math.max() instead.

Example

Math.max.apply(null,[1,2,3]); // Will also return 3

The Value of this

In JavaScript strict mode, the first argument becomes the value of this in the invoked function, even if the argument is not an object.
In "non-strict" mode, if the value of the first argument is null or undefined, it is replaced with the global object.

No comments:

Post a Comment

Recent Post

Parallel Task in .Net 4.0