JavaScript Tutorial/Function/Function Object

Материал из Web эксперт
Перейти к: навигация, поиск

Function.apply()

Syntax



function.apply()


Function.arguments

Syntax



function.arguments


Function.arity

The arity property represents the number of declared arguments a function expects to receive.

The arity property is valid when the language attribute of the script tag is set to JavaScript1.2.



<html>
    <body>
    <script lanuguage="JavaScript1.2">
    <!--
    function subtract(first, second){
      var result = first - second;
      return result;
    }
    document.write("arity = " + subtract.arity + "<br>")
    document.write("The result of the subtract function is: " + subtract(4,3));
    -->
    </script>
    </body>
    </html>


Function.call()

Syntax



function.call(this)
    function.call(this, arg1, arg2, ..., argN)


Function.caller

The caller property is used to reference the function that called the currently executing function.



<html>
    <body>
    <script lanuguage="JavaScript1.1">
    <!--
    function functionB(){
         var Boss = true;
         functionA();
    }
    function functionA(){
        myBoss = functionA.caller.name;
        document.write(myBoss + "<br>");
    }
    functionB();
    -->
    </script>
    </body>
    </html>


Function() (capital F)

Syntax



var variable = new Function()
    var variable = new Function(int)
    var variable = new Function(arg1, ..., argN)


Function() is a constructor that creates a Function object.

Properties and Methods of the Function Object

Property/Method Description apply() Applies method to multiple objects arguments Array reflecting function arguments arity Number of arguments expected by function call() Allows calling of methods belonging to other functions caller Reference to function caller prototype Prototype for a class of objects toSource() Created copy of function object toString() Converts function back to string which defines it

Function.prototype

Syntax



function.prototype.property
    function.prototype.method


Function.toSource()

The toSource() method can create a copy of an object.



<html>
    <body>
    <script lanuguage="JavaScript">
    <!--
        var aString = new String("This is the source");
        bString = aString.toSource();
        document.write(bString);
    -->
    </script>
    </body>
    </html>


Function.toString()

The toString() method is used to convert a function to string.

The method converts the function back to the JavaScript source.

The converted string includes all aspects of the defined function.



<html>
    <body>
    <script lanuguage="JavaScript">
    <!--
    function writeText(){
         document.write("Some dummy text");
    }
    var func = writeText.toString();
    document.write("The string representation of the writeText");
    document.write(" function looks like: " + "<br><br><b>");
    document.write(func + "</b>");
    -->
    </script>
    </body>
    </html>