Home > Article > Web Front-end > 4 ways to call functions in JavaScript code examples_javascript skills
1: Method calling mode
var myObj = {//对象字面量 param1: 1, param2: 2, sum: function (){ //this关键字只带当前的对象 return this.result = this.param1 + this.param2; } } myObj.sum(); //=>3
2: Function calling mode
var add = function(a, b){ return a + b; } //函数调用模式 add(1,2); //=>3
Alright
function add(a, b){ return a + b; } add(1,2);//=>3
3: Constructor calling mode
var add = function() { this.name = "汇智网"; this.sum = function (a, b){ return a + b; } } // 构造器调用模式 var obj = new add(); //obj是一个对象 obj.sum(1,2); //=>3
4: apply calling 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