JavaScript DHTML/Language Basics/Function

Материал из Web эксперт
Версия от 07:24, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Accepting Either One or No Arguments

   
<html>
<head>
  <title>JavaScript Unleashed</title>
  <script type="text/javascript">
  <!--
    function welcomeMessage(userName) {
      if (userName != null) {
        document.writeln("Hello, " + userName);
      }else{
        document.write("variable \"userName\" would show : ");
        document.writeln(userName);
      }
    }
  // -->
  </script>
</head>
<body>
  <script type="text/javascript">
  <!--
    document.writeln("First call to welcomeMessage(),\n");
    welcomeMessage("Mr.");
    document.writeln("<HR>\nSecond call to welcomeMessage(),\n");
    welcomeMessage();
  // -->
  </script>
</body>
</html>



A Function Can Be Set Up to Accept a Variable Number of Arguments

   
<html>
<head>
  <title>A Function Can Be Set Up to Accept a Variable Number of Arguments</title>
  <script type="text/javascript">
  <!--
    function welcomeMessage(userName) {
      if (userName != null) {
        document.writeln("Hello, " + userName);
      }else{
        document.writeln("Welcome to our Web site!");
      }
      numArgs = welcomeMessage.arguments.length;
      if(numArgs > 1) {
        for(var i = 1; i < numArgs; i++) {
          document.writeln("\""+welcomeMessage.arguments[i]+"\"");
        }
      }
    }
  // -->
  </script>
</head>
<body>
  <script type="text/javascript">
  <!--
    var userName = "David", extraMsg = "It has been a long time!";
    var userName2 = null;
    var extraMsg1 = "Would you like to become a member?";
    var extraMsg2 = "You can enroll online!";
    welcomeMessage(userName, extraMsg);
    document.writeln("<hr>");    welcomeMessage(userName2, extraMsg1, extraMsg2);
  // -->
  </script>
</body>
</html>



A Function Definition

   
<HTML>
<HEAD>
<TITLE>A function definition</TITLE>
<SCRIPT LANGUAGE="JavaScript"><!--
function displayTaggedText(tag, text) {
 document.write("<"+tag+">")
 document.write(text)
 document.write("</"+tag+">")
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript"><!--
displayTaggedText("H1","This is a level 1 heading")
displayTaggedText("P","This text is the first paragraph of the document.")
// -->
</SCRIPT>
</BODY>
</HTML>



A Function"s arguments and caller Properties

   
/*
JavaScript Bible, Fourth Edition
by Danny Goodman 
John Wiley & Sons CopyRight 2001
*/
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function hansel(x,y) {
    var args = hansel.arguments
    document.write("<P>hansel.caller is " + hansel.caller + "<BR>")
    document.write("hansel.arguments.length is " + hansel.arguments.length + "<BR>")
    for (var i = 0; i < args.length; i++) {
        document.write("argument " + i + " is " + args[i] + "<BR>")
    }
    document.write("</P>")
}
function gretel(x,y,z) {
    today = new Date()
    thisYear = today.getFullYear()
    hansel(x,y,z,thisYear)
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript"> 
hansel(1, "two", 3);
gretel(4, "five", 6, "seven");
</SCRIPT>
</BODY>
</HTML>



A function with arguments, that returns a value

   

<html>
<head>
<script type="text/javascript">
function total(a,b){
    return a + b
}
</script>
</head>
<body>
<script type="text/javascript">
    document.write(total(2,3))
</script>

</body>
</html>



A function with only one statement

   
<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
function yourMessage()
{
    alert("Your first function!");
}
</script>
</head>
<body>
</body>
</html>



Array filter and callback functions

   
<html>
<head>
<title>Array filter and callback functions</title>
</head>
<body>
<script type="text/javascript">
function checkColor(element,index,array) {
  return (element >= 0 && element < 256);
}
var colors = new Array(  );
colors[0] = [0,262,255];
colors[4] = [0,0,255];
colors[5] = [-5,567,255];
var testedColors = new Array(  );
for (var i in colors) {
   testedColors[i] = colors[i].filter(checkColor);
   document.write(testedColors[i]);
}

</script>
</body>
</html>



Call a javascript function with javascript:void()

  
<html>
<head>
    <title>Void</title>
</head>
<body>
<p><a href="javascript:void(window.open("http://www.google.ru/"))">
Click here to open a new window.</a></p>
</body>
</html>



Call function in body onload event

   
<html>
<head>
<title>Random Quote</title>
<script type="text/javascript">
function getQuote() {
   document.write("onload");
}
</script>
</head>
<body onload="getQuote();">
</body>
</html>



Calling a Function from an Event Handler

   
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function showMsg(msg) {
    alert("The button sent: " + msg)
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
    <INPUT TYPE="button" VALUE="Click Me" 
    onClick="showMsg ("The button has been clicked!")">
</FORM>
</BODY>
</HTML>



Calling a Generalizable Function

   
<HTML>
<HEAD>
<TITLE>Variable Scope Trials</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function factorial(n) {
    if (n > 0) {
        return n * (factorial(n - 1));
    } else {
       return 1;
    }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Enter an input value: <INPUT TYPE="text" NAME="input" VALUE=0>
<P><INPUT TYPE="button" VALUE="Calc Factorial" 
    onClick="this.form.output.value = factorial(this.form.input.value)">
<P>Results: <INPUT TYPE="text" NAME="output">
</FORM>
</BODY>
</HTML>



Call your function

   
<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
yourMessage();
function yourMessage()
{
    alert("Your first function!");
}
</script>
</head>
<body>
</body>
</html>



Check the function parameters

  
<head>
<title></title>
<script type = "text/javascript" >
function addNums(firstNum,secondNum) {
    if ((isNaN(firstNum)) || (isNaN(secondNum))) {
        alert("Arguments must be numbers.");
        return;
    }
    else if (firstNum > secondNum) {
        alert(firstNum + " is greater than " + secondNum);
    }
    else {
        return firstNum + secondNum;
    }
}
</script>
</head>
<body>
<script type = "text/javascript" >
document.write(addNums("aaa",3));
document.write("<BR>");
document.write(addNums(2,3));
</script>
</body>



Declaring a Function in the "head" Block

   
<html>
<head>
  <title>JavaScript Unleashed</title>
  <script type="text/javascript">
  <!--
    function defaultColors() {
      document.writeln("Inside of defaultColors()");
      document.fgColor = "black";
      document.bgColor = "white";    
    }
  // -->
  </script>
</head>
<body>
  <script type="text/javascript">
  <!--     
    document.writeln("Functions are scripts just waiting to run!");
    defaultColors();
    document.writeln("All done.");
  // -->
  </script>
</body>
</html>



Define a function to accept the string value

  
<html>
<head>
<title>My First Page</title>
<script type = "text/javascript">
function myFunc(textToAlert) {
    alert(textToAlert);
}
myFunc("This is a test");
</script>
</head>
<body>
</body>
</html>



Define function in JavaScript

   
<html>
<head>
<script type="text/javascript">
function myfunction(){
    alert("HELLO")
}
</script>
</head>
<body>
<form>
    <input type="button" onclick="myfunction()" value="Call function">
</form>

</body>
</html>



Funciton with arguments

   
<html>
<head>
<script type="text/javascript">
function myfunction(txt){
    alert(txt)
}
</script>
</head>
<body>
<form>
<input type="button" onclick="myfunction("Hello")" value="Call function">
</form>
</body>
</html>



Function is Object

   
<html>
<head>
<title>Function Object</title>
</head>
<body>
<script type="text/javascript">
function funcObject(x,y,z) {
   for (var i = 0; i < funcObject.length; i++) {
     document.writeln("argument " + i + ": " + arguments[i] + "<br />");
   }
}
funcObject(1,2,3);
</script>
</body>
</html>



Functions That Return Values Can Be Used in Expressions

   
/*
JavaScript Unleashed, Third Edition
by Richard Wagner and R. Allen Wyke 
ISBN: 067231763X
Publisher Sams CopyRight 2000
*/

<html>
<head>
  <title>JavaScript Unleashed</title>
  <script type="text/javascript">
  <!--
    function isPhone(aString) {
      var aChar = null;
      var status = true;
      if(aString.length != 13) {
        status = false;
      }else{
        for(var i = 0; i <= 12; i++) {
          aChar = aString.charAt(i);
          if ( i == 0 && aChar == "(" ){
            continue;
          }else{
            if( i == 4 && aChar == ")" ){
              continue;
            }else{
              if( i == 8 && aChar == "-" ){
                continue;
              }else{
                if( parseInt(aChar,10) >= 0 && parseInt(aChar,10) <= 9 ){
                  continue;
                }else {
                  status = false;
                  break;
                }
              }
            }
          }
        }
      }
      return(status);
    }
  // -->
  </script>
</head>
<body>
  <script type="text/javascript">
  <!--
    var userInput = "(800)555-1212";    
    
    if(isPhone(userInput)) {
      document.writeln("Thank you for your phone number.");
      document.writeln("I will have a representative get you");
      document.writeln("more information.");
    }else{
      document.writeln("Please re-enter your phone number");
      document.writeln("using the format (###)###-####");
    }
  //-->
  </script>
   
</body>
</html>



Function that returns a value

   
<html>
<head>
<script type="text/javascript">
function myFunction(){
    return ("Hello!")
}
</script>
</head>
<body>
<script type="text/javascript">
    document.write("return from function")
    document.write(myFunction())
</script>

</body>
</html>



Function That Wraps Document.Write, Adding a Line Break

   
<HTML>
<BODY>
<CENTER>
<H1>
<SCRIPT> 
   function myFunction (textIn) { 
      document.write (textIn + "<br>"); 
   } 
   myFunction ("I"); 
   myFunction ("did"); 
   myFunction ("it"); 
   myFunction ("my"); 
   myFunction ("way!"); 
   </SCRIPT>
</CENTER>
</H1>
</BODY>
</HTML>



Invoking third argument as function

   
<html>
<head>
<title>Pass Me</title>
</head>
<body>
<script type="text/javascript">
function funcObject(x,y,z) {
   alert(z(x,y));
}
// third parameter is function
funcObject(1,2,function(x,y) { return x * y});
</script>
</body>
</html>



Nested function call

   
<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
function firstMessage(){
    alert("A");
    secondMessage();
    alert("B");
}
function secondMessage()
{
    alert("another function");
}
</script>
</head>
<body onLoad="firstMessage()">
</body>
</html>



Passing by Reference Versus Passing by Value

   
/*
JavaScript Unleashed, Third Edition
by Richard Wagner and R. Allen Wyke 
ISBN: 067231763X
Publisher Sams CopyRight 2000
*/
<html>
<head>
  <title>JavaScript Unleashed</title>
  <script type="text/javascript">
  <!--
    // wrap and integer inside an object
    function intObject() {
      this.i;
      return this;
    }
   
    function start() {
      // declare two ways to store an integer
      var I;
      var myIntObject = new intObject();
   
      // assign initial values
      i = 0;
      myIntObject.i = 0;
   
      // display current values
      document.write("<br>Before<br>");
      document.write("i = " + i);
      document.write("<br>");
      document.write("myIntObject = " + myIntObject.i);
      document.write("<br>");
   
      // pass variables
      modify(i, myIntObject);
   
      // display current values
      document.write("<br>After<br>");
      document.write("i = " + i);
      document.write("<br>");
      document.write("myIntObject = " + myIntObject.i);
      document.write("<br>");
    }   
    function modify(n, obj) {
      n++;
      obj.i++;
    }
  //-->
  </script>
</head>
<body>
  <script type="text/javascript">
  <!--
    start();
  //-->
  </script>
</body>
</html>



Passing the Form Object as a Parameter

   
<HTML>
<HEAD>
<TITLE>Beatle Picker</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function processData(form) {
    for (var i = 0; i < form.items.length; i++) {
        if (form.items[i].checked) {
            break
        }
    }
    var choseItem = form.items[i].value
    var chosenSong = form.song.value
    alert("Looking to see if " + chosenSong + " was written by " + choseItem + "...")
}
function checkSong(songTitle) {
    var enteredSong = songTitle.value
    alert("Making sure that " + enteredSong + " was recorded by the items.")
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="Abbey Road">
Choose your favorite Beatle:
<INPUT TYPE="radio" NAME="items" VALUE="A" CHECKED="true">A
<INPUT TYPE="radio" NAME="items" VALUE="B">B
<INPUT TYPE="radio" NAME="items" VALUE="C">C
<INPUT TYPE="radio" NAME="items" VALUE="D">D
<P>
Enter the name of your favorite items song:<BR>
<INPUT TYPE="text" NAME="song" VALUE="value" onChange="checkSong(this)"><P>
<INPUT TYPE="button" NAME="process" VALUE="Process Request..." onClick="processData(this.form)">
</FORM>
</BODY>
</HTML>



Pass string value in and return string value out

   

<HTML>
<HEAD>
<SCRIPT language="JavaScript">
function myFunc(my, p)
{
   alert(my + " : " + p);
} 
function get_added_text() 
{
     var textpart1 = "A ";
     var textpart2 = "B";
     var added_text = textpart1 + textpart2;
     return added_text;
}
myFunc("A",1500);
var alert_text=get_added_text();
window.alert(alert_text);
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>



Pass variables to a function, and use these variable values in the function

   
<html> 
<head> 
<script type="text/javascript"> 
function myfunction(txt){ 
    alert(txt) 
} 
</script> 
</head> 
<body> 
<form> 
<input type="button" onclick="myfunction("Java!")" value="Java"> 
<input type="button" onclick="myfunction("Java too!")" value="Java too"> 
</form> 
</body> 
</html>



Return an incremented value

  
<head>
<title></title>
<script type = "text/javascript" >
function incrementNum(myNum) {
    if (isNaN(myNum)) {
        alert(myNum + " isn"t a number.");
        return;
    }
    return myNum + 1;
}
</script>
</head>
<body>
<script type = "text/javascript" >
alert(incrementNum(3));
</script>
</body>



Save returned value from a function to a variable

  
<head>
<title></title>
</head>
<body>
<script type = "text/javascript" >
function addNumbers() {
    firstNum = 4;
    secondNum = 8;
    result = firstNum + secondNum;
    return result;
}
result = 0;
alert(result);
sum = addNumbers();
alert(result);
</script>
</body>



setTimeout() with a pointer to a function

   
<html>
<head>
<script type="text/javascript">
function timeout(){
    window.setTimeout("show_alert()",2000)
}
function show_alert(){
    alert("hi")
}
</script>
</head>
<body>
<form>
<input type="button" onclick="timeout()" value="Count down">
</form>
</body>
</html>

////////////////////////////////////////
Hi Sirs/Madams of wbex.ru,
 
I came across an article on your site about "pointers to a function in
javascript", in use with setTimeout*.
Well, that very title shows you do not understand th parts of
javascript you are talking about well enough. However, when actually
reading the article it is revealed that your misunderstanding goes
even deeper.
That"s why I decided to send you this email and learn you a thing or
two about javascript.
 
First off, your example resorts to the use of setTimeout("show_alert()", 4000).
Obviously you are passing a string, not a pointer to a function. Now
there are two ways to call setTimeout, one with a string and one with
a function. The last version is pretty much like using a pointer to a
function, but there are some differences. However, when using that
title the correct way to call setTimeout, would have been
"setTimeout(show_alert, 4000)". And yes, it would actually have had
the same result as the given code. Also, do note that tis circumvents
the indirect usage of eval (which you probably know is evil), as eval
is what is used to make sense of the string that can be passed to
setTimeout.
 
Now as for function pointers in javascript. Javascript does not know
any pointers. This includes function pointers. However, this is no
loss, because javascript functions are different things than functions
are in most languages.
In javascript functions are values, just like numbers, booleans and
objects are. They can be treated as such in every respect and
additionally you can call them. As such, you can have function
constants. These are commonly known as anonymous functions and look
like this:
 
function (args) {/*body*/}
 
It also means you can assign a function value to a variable. Logically
this looks like this:
 
var variable = function (args) {/*body*/}
 
And now for the real magic of javascript, this line above is the real
meaning of the standard way to declare a function. Confused? Let me
show you:
 
function functionName (args) {/*body*/}
 
does the exact same thing as:
 
var functionName = function (args){/*body*/}
 
This alternate syntax was simply added to have the functions appear to
work as in other languages, but as you have jut seen, they do work
slightly different. However, this way in which they do work is a more
powerful way. For example, we do not need a concept such as a function
pointer, we can simply require an argument to be a function. From
there on, a programmer can decide to supply a variable which holds a
function (the thing I did above in your sample), or one can decide to
supply a function literal. In that case you example would look like
this:
 
function timeout()
{
   setTimeout(function()
   {
       alert("hi");
   }, 4000);
}
 
Of course, the spacing could be altered to put all of this on one line.
 
I hope I taught you a little about javascript and I hope this may
serve as a way to decrease the amount of faulty information about the
intricacies of javascript in the top results of google search.
 
Yours sincerely,
 
Jasper Horn
jasperhorn at gmail.ru



Show Arguments

   
<html>
<script>
<!--
function showArgs(a, b, c) {
   var argList = "";
   for (var n=0; n <= arguments.length; n++) {
       argList += n + ". " + arguments[n] + "\n";
   }
   alert(argList);
}
showArgs("java", "script");
//-->
</script>
</html>



Simplest function

   
<html>
<head>
<script language="JavaScript">
<!--
function TestFunction() {
  var localVar = "Hello";
}
alert(localVar);
//-->
</script>
</head>
</html>



Using an Argument with a JavaScript Function

   
<html>
<head>
  <title>JavaScript Unleashed</title>
</head>
<body>
  <script type="text/javascript">
  <!-- 
    function getBinary(anInteger) {
      var result = "";
      var shortResult = "";
      for(var i=1; i <= 32; i++) {
        if(anInteger & 1 == 1) {
            result = "1" + result;
            shortResult = result;
        } else {          
            result =  "0" + result;
        }
        anInteger = anInteger >> 1;
      }
      return(shortResult);
    }
    var binaryString = "";
   
    x = 127;
    binaryString = getBinary(x);
   
    document.write("The number " + x + " in binary form is : \n");
    document.writeln(binaryString);
    
    x = 255;
    binaryString = getBinary(x);
   
    document.write("The number " + x + " in binary form is : \n");
    document.writeln(binaryString);
    document.writeln("The variable x is still equal to : " + x);
  // -->
  </script>
   
</body>
</html>



Using the Function Object

   
<HTML>
<HEAD>
<TITLE>Using the Function Object</TITLE>
<BODY><H1>
<SCRIPT LANGUAGE="JavaScript"><!--
addBraces = new Function("s","return "["+s+"]"")
document.write(addBraces("This"))
document.write(addBraces("is"))
document.write(addBraces("a"))
document.write(addBraces("test."))
// --></SCRIPT>
</H1></BODY>
</HTML>



Variable Scope Workbench Page

   
/*
JavaScript Bible, Fourth Edition
by Danny Goodman 
John Wiley & Sons CopyRight 2001
*/
<HTML>
<HEAD>
<TITLE>Variable Scope Trials</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var headGlobal = "Gumby"
function doNothing() {
    var headLocal = "Pokey"
    return headLocal
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
// two global variables
var aBoy = "Charlie Brown"
var hisDog = "Snoopy"
function testValues() {
    var hisDog = "Gromit"  // initializes local version of "hisDog"
    var page = ""
    page += "headGlobal is: " + headGlobal + "<BR>"
    // page += "headLocal is: " + headLocal + "<BR>" // : headLocal not defined
    page += "headLocal value returned from head function is: " + doNothing() + "<P>"
    page += " aBoy is: " + aBoy + "<BR>" // picks up global
    page += "local version of hisDog is: " + hisDog + "<P>" // "sees" only local
    document.write(page)
}
testValues()
document.write("global version of hisDog is intact: " + hisDog)
</SCRIPT>
</BODY>
</HTML>