This article mainly introduces four code examples for calling functions in JavaScript, this article provides code instances in four modes: method call mode, function call mode, constructor call mode, and apply call mode. For more information, see
1: method call mode
Var myObj = {// object literal param1: 1, param2: 2, sum: function () {// this keyword only includes the current object return this. result = this. param1 + this. param2;} myObj. sum (); // => 3
2: function call mode
Var add = function (a, B) {return a + B;} // function call mode add (1, 2); // => 3
Yes
function add(a, b){ return a + b;}add(1,2);//=>3
3: constructor call mode
Var add = function () {this. name = "Huizhi Network"; this. sum = function (a, B) {return a + B ;}// constructor call mode var obj = new add (); // obj is 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