JavaScript DHTML/Language Basics/Function

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

Содержание

Accepting Either One or No Arguments

   <source lang="html4strict">
  

<html> <head>

 <title>JavaScript Unleashed</title>
 <script type="text/javascript">
 
 </script>

</head> <body>

 <script type="text/javascript">
 
 </script>

</body> </html>



 </source>
   
  


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

   <source lang="html4strict">
  

<html> <head>

 <title>A Function Can Be Set Up to Accept a Variable Number of Arguments</title>
 <script type="text/javascript">
 
 </script>

</head> <body>

 <script type="text/javascript">
 
 </script>

</body> </html>



 </source>
   
  


A Function Definition

   <source lang="html4strict">
  

<HTML> <HEAD> <TITLE>A function definition</TITLE> <SCRIPT LANGUAGE="JavaScript"> </SCRIPT> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> </SCRIPT> </BODY> </HTML>



 </source>
   
  


A Function"s arguments and caller Properties

   <source lang="html4strict">
  

/* 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("

hansel.caller is " + hansel.caller + "
") document.write("hansel.arguments.length is " + hansel.arguments.length + "
") for (var i = 0; i < args.length; i++) { document.write("argument " + i + " is " + args[i] + "
") } document.write("

")

} 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>



 </source>
   
  


A function with arguments, that returns a value

   <source lang="html4strict">
  

<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>



 </source>
   
  


A function with only one statement

   <source lang="html4strict">
  

<html> <head> <title>A Simple Page</title> <script language="JavaScript"> function yourMessage() {

   alert("Your first function!");

} </script> </head> <body> </body> </html>


 </source>
   
  


Array filter and callback functions

   <source lang="html4strict">
  

<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>


 </source>
   
  


Call a javascript function with javascript:void()

   <source lang="html4strict">
 

<html> <head>

   <title>Void</title>

</head> <body>

<a href="javascript:void(window.open("http://www.google.ru/"))"> Click here to open a new window.</a>

</body> </html>


 </source>
   
  


Call function in body onload event

   <source lang="html4strict">
  

<html> <head> <title>Random Quote</title> <script type="text/javascript"> function getQuote() {

  document.write("onload");

} </script> </head> <body onload="getQuote();"> </body> </html>


 </source>
   
  


Calling a Function from an Event Handler

   <source lang="html4strict">
  

<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>



 </source>
   
  


Calling a Generalizable Function

   <source lang="html4strict">
  

<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>

<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> </source>

Call your function

   <source lang="html4strict">
  

<html> <head> <title>A Simple Page</title> <script language="JavaScript"> yourMessage(); function yourMessage() {

   alert("Your first function!");

} </script> </head> <body> </body> </html>


 </source>
   
  


Check the function parameters

   <source lang="html4strict">
 

<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("
"); document.write(addNums(2,3)); </script> </body>


 </source>
   
  


Declaring a Function in the "head" Block

   <source lang="html4strict">
  

<html> <head>

 <title>JavaScript Unleashed</title>
 <script type="text/javascript">
 
 </script>

</head> <body>

 <script type="text/javascript">
 
 </script>

</body> </html>



 </source>
   
  


Define a function to accept the string value

   <source lang="html4strict">
 

<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>


 </source>
   
  


Define function in JavaScript

   <source lang="html4strict">
  

<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>



 </source>
   
  


Funciton with arguments

   <source lang="html4strict">
  

<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>



 </source>
   
  


Function is Object

   <source lang="html4strict">
  

<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] + "
"); }

} funcObject(1,2,3); </script> </body> </html>


 </source>
   
  


Functions That Return Values Can Be Used in Expressions

   <source lang="html4strict">
  

/* 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">
 
 </script>

</head> <body>

 <script type="text/javascript">
 
 </script>
  

</body> </html>



 </source>
   
  


Function that returns a value

   <source lang="html4strict">
  

<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>



 </source>
   
  


Function That Wraps Document.Write, Adding a Line Break

   <source lang="html4strict">
  

<HTML> <BODY>

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

</BODY> </HTML>



 </source>
   
  


Invoking third argument as function

   <source lang="html4strict">
  

<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>


 </source>
   
  


Nested function call

   <source lang="html4strict">
  

<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>


 </source>
   
  


Passing by Reference Versus Passing by Value

   <source lang="html4strict">
  

/* 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">
 
 </script>

</head> <body>

 <script type="text/javascript">
 
 </script>

</body> </html>



 </source>
   
  


Passing the Form Object as a Parameter

   <source lang="html4strict">
  

<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:
<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>



 </source>
   
  


Pass string value in and return string value out

   <source lang="html4strict">
  

<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>


 </source>
   
  


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

   <source lang="html4strict">
  

<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>



 </source>
   
  


Return an incremented value

   <source lang="html4strict">
 

<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>


 </source>
   
  


Save returned value from a function to a variable

   <source lang="html4strict">
 

<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>


 </source>
   
  


setTimeout() with a pointer to a function

   <source lang="html4strict">
  

<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



 </source>
   
  


Show Arguments

   <source lang="html4strict">
  

<html> <script>

</script> </html>



 </source>
   
  


Simplest function

   <source lang="html4strict">
  

<html> <head> <script language="JavaScript">

</script> </head> </html>



 </source>
   
  


Using an Argument with a JavaScript Function

   <source lang="html4strict">
  

<html> <head>

 <title>JavaScript Unleashed</title>

</head> <body>

 <script type="text/javascript">
 
 </script>
  

</body> </html>



 </source>
   
  


Using the Function Object

   <source lang="html4strict">
  

<HTML> <HEAD> <TITLE>Using the Function Object</TITLE>

<BODY>

<SCRIPT LANGUAGE="JavaScript"></SCRIPT>

</BODY>

</HTML>



 </source>
   
  


Variable Scope Workbench Page

   <source lang="html4strict">
  

/* 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 + "
" // page += "headLocal is: " + headLocal + "
" // : headLocal not defined page += "headLocal value returned from head function is: " + doNothing() + "<P>" page += " aBoy is: " + aBoy + "
" // 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>



</source>