Home >Web Front-end >JS Tutorial >Simple usage of apply and call in js
Call and apply appear to dynamically change this. When an object does not have a certain method, but others do, we can use call or apply to operate with the methods of other objects. In this article, we mainly share with you the simple usage of apply and call in js, hoping to help everyone.
call and apply are methods of Function.prototype, which are implemented internally by the JavaScript engine. Because they belong to Function.prototype, each Function object instance, that is, each method has call and apply attributes. .Since they are attributes of methods, their use is of course specific to methods. These two methods are easily confused because they have the same function, but they are just used in different ways.
It can be concluded from the above call, apply is used for methods, in order to change the this pointer of calling the method
Simple example:
call
function A() { this.getName = function (xx) { return xx; } } function B() { } var a = new A(); console.log( a.getName('i am A') ); //i am A var b = new B() ; console.log( a.getName.call(b,'i am B') ); // i am B
There is no method in function B. Function A has a getName() method. a.getName() is naturally established, but what should I do if B also needs to use the getName() method? Then use call(this,'parameter')! !
You can understand this sentence again - we can use call or apply to call other objects' methods to operate. Call and apply appear to dynamically change this. Originally a.getName()'s this points to a, call dynamically points this to b and becomes b.getName()
apply
apply and call only use different parameters.
function A() { this.sun = function (a ,b) { return a+b; } } function B() { } var a = new A(); console.log( a.sun(1,2) ); //3 var b = new B() ; console.log( a.sun.call(b,2,2) ); // 4 console.log( a.sun.apply(b,[3, 3]) ); //6
General usage of call and apply
The dom selected through document.getElementsByTagName is used more often. Node is an array-like array. It cannot apply push, pop and other methods under Array. We can pass:
var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));
so that domNodes can apply all methods under Array.
Related recommendations:
How to use call and apply in JavaScript to implement inheritance usage detailed explanation
call, apply, What does bind do? Why use them?
Detailed explanation of the difference between apply and call in JavaScript
The above is the detailed content of Simple usage of apply and call in js. For more information, please follow other related articles on the PHP Chinese website!