Home  >  Article  >  Web Front-end  >  4 ways to call functions in JavaScript code examples_javascript skills

4 ways to call functions in JavaScript code examples_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:50:551129browse

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


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