JavaScript function call pattern

Source: Internet
Author: User

1. Method Invocation Mode:

var myObj = {    value:0;    Increment:function (inc) {        This.value + = typeof Inc = = = ' number '? Inc:1;    }} Myobj.increment (); Console.info (Myobj.value); 1        

  

2. Function call Mode:

When a function is not a property of an object, then it is used as a function, and this is bound to the global object, in order to solve this problem, we need to rename a variable internally. Get control of an intrinsic function

myobj.double = function () {    var _self = this;    var helper = function () {        _self.value = Add (_self.value,_self.value);    }    Helper (); Function call Helper};myobj.double (); Console.info (Myobj.value);

  

3. Constructor Mode:

If you call with new in front of a function, you will create a new object that hides the prototype that is connected to the function, and this will be bound to the new object.

var Quo = function (str) {    this.status = str;} Quo.prototype.get_status = function () {    return this.status;} Constructs a Quo instance var myquo = new Quo ("abc"); Console.info (Myquo.get_status ());

  

4. Apply Mode:

The Apply method constructs a parameter array and uses it to invoke the function, and allows us to select the this value, apply receives two parameters, one is the value that will be bound to this, and the other is the parameter array.

var arr = [3,4];var sum = add.apply (Null,arr);//Constructs an object containing the status member var statusobj = {    Status: "OK"};//statusobj does not inherit from Qu O.prototype, but the Get_status method can be raised in Statusobj, although Statusobj does not have a method named Get_status. var status = Quo.prototype.get_status.apply (Statusobj); Console.info (status);  "OK"

JavaScript function call pattern

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.