Four methods of calling functions in JavaScript: code example _ javascript skills

Source: Internet
Author: User
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

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.