Some time ago in the process of using JavaScript encountered the problem of inheritance, by the way the call () and the Apply () method to understand.
Two methods in common: the two methods have the same effect and are used to change the object of the current function call, that is, to change the direction of this.
The difference between the two methods: the difference is that the two methods differ in the way they are transmitted, and apply accepts the array parameters, and call accepts continuous parameters.
Definition of the Apply () method:
Function.apply (Obj,args);
OBJ: This object replaces the This object that is pointed inside the function class.
Args: This is an array that is passed as a parameter to the function.
Example:
<script>functionIntro (name,age) { This. name=name; This. age=Age ; This. speak=function() {Console.log (' My name is ' + This. name+ '. ' + ' I am ' + This. age+ ' years old. '); }}functionIntroinh (name,age) {intro.apply ( This, arguments); }varlm=NewIntroinh (' liming ', 20); Lm.speak ();</script>
The code above does a simple inheritance application and also shows the role of apply ().
Definition of the call () method:
Function.call (obj,[param1[,param2[,... [, Paramn]]]) ;
OBJ: This object replaces the This object that is pointed inside the function class.
Params: This is a list of parameters.
Example:
<script>functionIntro (name,age) { This. name=name; This. age=Age ; This. speak=function() {Console.log (' My name is ' + This. name+ '. ' + ' I am ' + This. age+ ' years old. '); }}functionIntroinh (name,age) {//intro.apply (this,arguments);Intro.call ( This, name,age);//Compare the above apply () difference;}varlm=NewIntroinh (' liming ', 20); Lm.speak ();</script>
Here only a simple concept and application of the narrative, the specific application of the project also requires our further practice.
A summary of the call () and apply () methods in JavaScript