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

4 ways to call functions in JavaScript code examples_javascript skills

WBOY
Release: 2016-05-16 15:50:55
Original
1165 people have browsed it

1: Method calling mode

var myObj = {//对象字面量
  param1: 1,
  param2: 2,
  sum: function (){
//this关键字只带当前的对象
return this.result = this.param1 + this.param2;
  }
}
myObj.sum(); //=>3
Copy after login

2: Function calling mode

var add = function(a, b){
  return a + b;
}
//函数调用模式
add(1,2); //=>3
Copy after login

Alright

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

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
Copy after login

4: apply calling mode

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

You can also use call

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


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template