Home >Web Front-end >JS Tutorial >Simple understanding of call and apply in Javascript

Simple understanding of call and apply in Javascript

高洛峰
高洛峰Original
2016-11-19 11:19:581129browse

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,[]);

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.


Statement:
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
Previous article:JS seamless scrollingNext article:JS seamless scrolling