4 ways to call a function in JavaScript code instance _javascript tips

Source: Internet
Author: User

1: Method Invocation pattern

var myobj = {//object literal
  param1:1,
  param2:2,
  sum:function () {
//this keyword with only 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

It's OK

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

3: Constructor Call pattern

var add = function () {
  this.name = "remit Wisdom net";
  This.sum = function (A, b) {return
    a + b;
  }
}
constructor invocation pattern
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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.