Four ways to call a function in JavaScript code instances

  • 2020-07-21 06:47:25
  • OfStack

1: Method invocation pattern


var myObj = {// Object literal 
  param1: 1,
  param2: 2,
  sum: function (){
//this Keywords carry only the current object 
return this.result = this.param1 + this.param2;
  }
}
myObj.sum(); //=>3

2: Function call pattern


var add = function(a, b){
  return a + b;
}
// Function call pattern 
add(1,2); //=>3

You can also


function add(a, b){
  return a + b;
}
add(1,2);//=>3

3: Constructor invocation pattern


var add = function() {
  this.name = " Huizhi network ";
  this.sum = function (a, b){
    return a + b;
  }
}
//  The constructor calls the pattern 
var obj = new add(); //obj is 1 An object 
obj.sum(1,2); //=>3

4: apply call mode


var add = function (a, b) {
  return a + b;
}
 
add.apply(null,[1,2]); //=>3

You can also use call


var add = function (a, b) {
  return a + b;
}
add.call(null,1,2); //=>3



Related articles: