Fully understand the properties and methods of function objects in JavaScript

Source: Internet
Author: User

Functions are the basic data types in JavaScript, and some properties and methods are defined on the object of the function, and we will introduce these properties and methods, which is helpful for understanding the inheritance mechanism of JavaScript.

  1. Attributes (properties)
    • arguments

      Gets all parameters of the currently executing Function object, which is an array-like but not an array object, saying that it resembles an array because it has an array-like access property and a way to access the value of the corresponding single parameter by arguments[n] and has the length property of the array. Also, the arguments object stores the arguments that are actually passed to the function, not limited to the argument list (length) defined by the function declaration, and the arguments object cannot be created explicitly. The following sample illustrates these properties.

      function Testarg (A, b) {    var actcount = arguments.length,        expcount = testarg.length,        result;    result = "Expected arguments ' count is" + Expcount + ";<br/>";    Result + = "Actual arguments ' count is" + Actcount + ".<br/>";    Result + = "they are:<br/>";    for (var i = 0; i < Actcount; i++) {        result + = Arguments[i] + ";<br/>";    }    if (arguments instanceof Array) {        result + = "Arguments is an array instance."    } else if (arguments instanceof Ob ject) {        result + = "Arguments is an Object instance."    }    document.write (result);} Testarg (1);//output result is:expected arguments ' count is 2; Actual arguments ' Count is 1.They are:1;arguments are an Object instance.
    • length

      Gets the number of parameters defined by the function,

      functionname.length

      The

      is different from arguments.length, which we have described above. Because JavaScript calls functions without any number and type checking of function arguments, there is no concept of function invocation errors. But we can use the difference between functionname.length and arguments.length to detect the number of parameters inside the function call.

       function Checkvarcount (A, B) {if (checkvarcount.length!== arguments . length) {alert ("The count of the parameters passed into the function doesn ' t match the function definition."    ); } alert ("Successfully call the function");} Checkvarcount (1, 2);//successfully Call the Functioncheckvarcount (1)//the count of the parameters your passed into the fun Ction doesn ' t match the function definition. 
    • caller

      Gets the function that called the current function. The caller property is defined only when the function is executing.

      functionname.caller

      If the function is called from the top level of the JAVASCRIPT program, caller contains null. If you use the Caller property in a string context, the result is the same as functionname.tostring, which means that the inverse of the function is displayed.

       function test () {if (Test.caller = = null) {document.write ("tes    T is called from the toppest level ");        } else {document.write ("test is called from the Function:<br/>");    Document.writeln (Test.caller.toString ()); } document.write ("<br/>");} Call from the top leveltest (),//output:test is called from the Toppest levelfunction testouter () {test ();}  Call from the function Testoutertestouter ();//output://test was called from the Function://function Testouter () {test (); } 
    • callee

      Returns the function object being executed, which is the body of the specified function object.

      [functionname.] The Arguments.callee

      Callee property is a member of the arguments object that is available only when the related function is executing. Typically this property is used to recursively invoke anonymous functions.

       var fac = function (n) {if (n <= 0) return 1; else return n * Arguments.callee (n-1);} (4);d ocument.write (FAC);//24 
    • constructor

      Gets the function that creates an object. The constructor property is a prototype member of each object that has a prototype. This includes all internal JavaScript objects except the Global and Math objects. The constructor property is the function reference used to construct an object instance.

      //A constructor function.function MyObj () {this.number = 1;} var x = new String ("Hi"), if (x.constructor = = string) document.write ("Object is a string."); document.write ("<br/>"); var y = new Myobj;if (Y.constructor = = MYOBJ) document.write ("Object constructor is MyO BJ. "); /output://object is a String.//object constructor is MYOBJ. 
    • Prototype

      Gets the prototype of the object. Each constructor has a prototype property that points to another object. All properties and methods of this object are inherited by an instance of the constructor. This means that we can define the invariant properties and methods directly on the prototype object.

      Function man (name, age) {    this.name = name;    This.age = age;} Man.prototype.sex = "M"; Man.prototype.struggle = function () {    alert ("Day!!!!");} var li = new man ("Leo"), alert (li.sex);//mli.struggle ();//day Day UpMan.prototype.isStrong = True;alert (Li.isstrong) ;//true

      This way we can also append methods and properties to the defined objects, including native objects provided by JavaScript.

      var AA = new number (2); alert (typeof (Aa.add)); UndefinedNumber.prototype.add = function (add1) {    return this + add1;} Alert (Aa.add (1)); 3
  2. Method
    • Apply

      Invokes the function and replaces the function's this value with the specified object, replacing the function's arguments with the specified array.

      Functionname.apply ([Thisobj[,argarray]])

      If Argarray is an invalid value, an "Object expected" error is thrown, and if neither thisobj nor Argarray is provided, the current this is used as the Thisobj

      function CallMe (arg1, arg2) {var s = "";    s + = "This value:" + this;    s + = "<br/>";        For (i in callme.arguments) {s + = "arguments:" + callme.arguments[i];    s + = "<br/>"; } return s;} document.write ("Original function: <br/>");d Ocument.write (CallMe (1, 2));d ocument.write ("<br/>"); document.write ("Function called with apply: <br/>");d Ocument.write (callme.apply (3, [4, 5]);d Ocument.write (" <br/> ");d ocument.write (" Function called with Apply with invalid array: <br/> "); try{document.write (callMe. Apply (3,2));} catch (E) {document.write (e.message);} document.write ("<br/><br/>");d ocument.write ("Function called with the Apply without any argument: <br/>    ");d Ocument.write (callme.apply ());//output result://original function://this value: [Object window]//arguments:1// Arguments:2//function called with apply://this value:3//arguments:4//arguments:5//function called with APPL Y with InvalID Array://function.prototype.apply:arguments list have wrong type//function called with apply without any argument://th Is value: [Object Window]
    • Pager

      Invokes the method of an object, replacing the current object with another object.

      Call ([thisobj[, arg1[, arg2[, [, ArgN]]])

      It allows you to change the function's this object from the initial context to the new object specified by Thisobj. If the Thisobj parameter is not provided, the global object is used as the thisobj. The only difference from the Apply method is that the second argument type of apply must be an array, and the call method enumerates all the arguments, separated by commas.

      function CallMe (arg1, arg2) {    var s = "";    s + = "This value:" + this;    s + = "<br/>";    For (i in callme.arguments) {        s + = "arguments:" + callme.arguments[i];        s + = "<br/>";    }    return s;} document.write ("Original function: <br/>");d Ocument.write (CallMe (1, 2));d ocument.write ("<br/>"); document.write ("Function called with Call: <br/>");d Ocument.write (Callme.call (3, 4, 5));//Output://Original Function://This value: [Object window]//arguments:1//arguments:2//Function called with Call://This value:3//arg uments:4//Arguments:5

    • Bind

      For a given function, create a binding function with the same body as the original function. In the binding feature, the This object resolves to an incoming object. The binding function has the specified initial parameters.

      Function.bind (Thisarg[,arg1[,arg2[,argn]])

      where function, Thisarg is the required option. Returns a new function that is the same as the function function, except that the this object and the parameter are different.

      Define the original Function.var checknumericrange = function (value) {    if (typeof value!== ' number ')        return F Alse;    else        return value >= this.minimum && value <= this.maximum;} The Range object would become the this value in the callback Function.var range = {minimum:10, maximum:20};//Bind t  He checknumericrange Function.var Boundchecknumericrange = checknumericrange.bind (range);//Use the new function to check Whether in the numeric range.var result = Boundchecknumericrange;d ocument.write (result);//Output:true

      The following code shows how to use the ARG1[,ARG2[,ARGN]]] parameter. The binding function uses the parameters specified in the Bind method as the first and second arguments. When the binding function is called, any parameters specified will be used as the third, fourth parameter (and so on).

      Define the original function with four Parameters.var Displayargs = function (Val1, Val2, Val3, Val4) {    
      Use the Bind method inside an object definition to bind an event to a method inside the object.
      <input type= "button" id= "Start" value= "Start"/><input type= "button" id= "Stop" value= "Stop"/><script        Type= "Text/javascript" > Function Car (owner) {this.owner = owner;            This.start = function () {//start the car console.log (this); Output:car {owner: "Mike", Start:function, stop:function} check.html:14 Console.log (This.owner + "s Car I            s starting. ");         Output:mike ' s car is starting.        };            This.stop = function () {console.log (this); Output: <input type= "button" id= "Stop" value= "Stop"/> Console.log (This.owner + "s car is starting.")            ;        Output:undefined ' s car is stopping.    }; } var btnstart = document.getElementById ("Start"), Btnstop = document.getElementById ("Stop"), Somecar = n    EW Car ("Mike");        if (document.attachevent) {btnstart.attachevent ("OnClick", SomeCar.start.bind (Somecar)); BtnsTop.attachevent ("OnClick", somecar.stop);        } else if (Document.addeventlistener) {Btnstart.addeventlistener ("click", SomeCar.start.bind (Somecar), false);    Btnstop.addeventlistener ("Click", Somecar.stop, false); }</script>

      From the above sample we found that when the bind method is not used, the event inside this point of the trigger click event DOM element input, it certainly does not have the Owner property; If you use bind to specify the object inside the event, you can achieve the desired effect.

    • Tostring

      Returns the string representation of an object.

      Objectname.tostring ([radix])

      ObjectName required to specify the object that needs to get the string representation. Radix optional, to specify a cardinality for converting numeric values to strings, this value is used only for numbers.

      The ToString method is a member of all built-in JavaScript objects. Its behavior depends on the type of object:

      Object Behavior
      Array Converts the element of an Array to a string. The resulting strings are concatenated, separated by commas.
      Boolean Returns "true" if the Boolean value is true. Otherwise, "false" is returned.
      Date Returns the text representation of a date.
      Error Returns a string containing the associated error information.
      Function Returns a string in the following format, where functionname is the name of a function that is called by the ToString method of the function:

      function functionname () {[native code]}

      Number Returns the literal representation of a number.
      String Returns the value of a String object.
      Default Returns "[Object ObjectName]", where ObjectName is the name of the object type.
    • ValueOf

      Returns the native value of the object.

      Object.valueof ()

      Each object within JavaScript defines a different valueof:

      Object Return Value
      Array Returns an array instance.
      Boolean Boolean value.
      Date The stored time value, in milliseconds, that starts at midnight UTC January 1, 1970.
      Function function itself.
      Number numeric value.
      Object The object itself. This is the default value.
      String The string value.

      Neither the Math nor the Error object has a ValueOf method.

Fully understand the properties and methods of function objects in JavaScript

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.