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

Simple understanding of call and apply in Javascript

高洛峰
Release: 2016-11-19 11:19:58
Original
1101 people have browsed it

The object-oriented capability in JavaScript was added later. For the sake of compatibility, many strange things were created,

function Animal(){    
    this.name = "Animal";    
    this.showName = function(){    
        alert(this.name);    
    }    
}    
  
function Cat(){    
    this.name = "Cat";    
}    
   
var animal = new Animal();    
var cat = new Cat();    
    
//通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。    
//输入结果为"Cat"    
animal.showName.call(cat,",");    
//animal.showName.apply(cat,[]);
Copy after login

So, it can be seen that call and apply appear to dynamically change this. When an object There is no certain method, but there are others. We can use the methods of other objects to operate using call or apply.


The most commonly used one is that the dom node selected through document.getElementsByTagName 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("*"));
In this way, domNodes can apply all methods under Array.


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