Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / NewStats: 3,208,055 members, 8,001,289 topics. Date: Wednesday, 13 November 2024 at 08:12 AM |
Nairaland Forum / Science/Technology / Webmasters / Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] (3424 Views)
Object Oriented Programing And Procedural Programing In Php What Is The Diff? / Procedural Vs Object Oriented PHP / How To Implement Captcha(made Simple On Procedural Php) (2) (3) (4)
Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 5:06pm On Jun 02, 2009 |
Hi y'all, i have had multiple requests over time to start a real javascript thread helping those that are not good with writing javascript utilities all by themselves. So i will be focusing on the following area: 1. Plain javascript for beginners 2. Object oriented stuffs [functions, classes] 3. Ajax [Asynchrochronous Javascript] 4. Libraries such as jquery Some areas such as how to control objects on the web page like images, and other web elements will also be discussed. Somewhere in this tutorial, newbies that are attentive will be able to build dynamic applications like a simple chat And any question concerning javascript will be entertained by both newbies and veterans as well. . . |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 5:32pm On Jun 02, 2009 |
The only requirement to join this class is that you must HTML (HyperText Markup Language) to an extent. If you are not sureif you meet this requirement, please check [url=http://]How To Build Your First Website And Upload It Online In Less Than 1 Week [written by DHTML]https://www.nairaland.com/nigeria?topic=213936.0[/url] Javascript is a client-sided language, meaning that it runs inside the web browser unlike them php which are executed on the server and the output sent to the browser. That is why javascript does not direct access to files stored on your web server. Also due to security restrictions, javascript does not have exclusive access to your client files. However, with some plugins and other stuffs, these bridges can easily be bypassed. so, to utilize javascript, you need to first learn how to define the script tag: an example is shown below: jscript.html <html> That will display a simple alert prompt. Following this, i am going to do some discussions on the javascript language: talking about stuffs like variables, strings, arrays and all those stuffs, before now coming to talk about the interaction of jscript with web page elements. . . |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by segsalerty(m): 8:22pm On Jun 02, 2009 |
cool tutorialfor beginners abeg roll on |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by joyblinks(f): 9:46pm On Jun 03, 2009 |
@dhtml pls continue. i interestd in it ohhh |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 2:28am On Jun 04, 2009 |
Today, we are going to be talking about writing your Javascript Code Just scroll through it, if you do not understand, dont worry, it is not yet time to start craming codes, just tryin to show you the style of the jscript language. Like many other programming languages, Microsoft JScript is written in text format, and is organized into statements, blocks consisting of related sets of statements, and comments. Within a statement you can use variables, immediate data such as strings and numbers, and expressions. Statements A JScript code statement consists of one or more items and symbols on a line. A new line begins a new statement, but it is a good idea to terminate your statements explicitly. You can do this with the semicolon (, which is the JScript termination character. aBird = "Robin";A group of JScript statements that is surrounded by braces ({}) is called a block. Blocks of statements are used, for example, in functions and conditionals. In the following example, the first statement begins the definition of a function, which consists of a block of five statements. The last three statements, which are not surrounded by braces, are not a block and are not part of the function definition. function convert(inches) {Comments A single-line JScript comment begins with a pair of forward slashes (//). A multiline comment begins with a forward slash and asterisk in combination (/*), and ends with the reverse (*/). aGoodIdea = "Comment your code thoroughly."; // This is a single-line comment. /* This is a multiline comment that explains the preceding code statement. The statement assigns a value to the aGoodIdea variable. The value, which is contained between the quote marks, is called a literal. A literal explicitly and directly contains information; it does not refer to the information indirectly. (The quote marks are not part of the literal.) */ // This is another multiline comment, written as a series of single-line comments. // After the statement is executed, you can refer to the content of the aGoodIdea // variable by using its name, as in the next statement, in which a string literal is // appended to the aGoodIdea variable by concatenation to create a new variable. var extendedIdea = aGoodIdea + " You never know when you'll have to figure out what it does."; Assignments and Equality The equal sign (=) is used in JScript to indicate the action of assigning a value. That is, a JScript code statement could say anInteger = 3; It means "Assign the value 3 to the variable anInteger," or "anInteger takes the value 3." When you want to compare two values to find out whether they are equal, use a pair of equal signs (==). This is discussed in detail in Controlling Program Flow. Expressions A JScript expression is something that a person can read as a Boolean or numeric expression. Expressions contain symbol characters like "+" rather than words like "added to". Any valid combination of values, variables, operators, and expressions constitutes an expression. var anExpression = "3 * (4 / 5)"; |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 2:42am On Jun 04, 2009 |
Creating Variables in Javascript This is a very key area in javascript because variables in javascript is different from any other language. Variables are used in Microsoft JScript to store values in your scripts. They are a way to retrieve and manipulate values using names. When used effectively then can help in understanding what a script does. Declaring Variables Although not required, it is considered good practice to declare variables before using them. You do this using the var statement. The only time you must use the var statement is when declaring variables that are local to a function. Local variables are those that are only within the function. At all other times, using the var statement to declare variables before their use is a recommended practice. The following code examples are of variable declaration: var mim = "A man, a plan, a canal, Panama!"; // The value stored in mim is of string type.Naming Variables JScript is a case-sensitive language, so naming a variable myCounter is different from naming it MYCounter. In addition, variable names, which can be of any length, must follow certain rules: The first character must be a letter (either uppercase or lowercase) or an underscore (_), or a dollar sign ($). Subsequent characters can be letters, numbers, underscores, or dollar signs. The variable name can't be a reserved word. Some examples of valid variable names: _pagecount Part9 Number_Items Some invalid variable names: 99Balloons // Starts with a number. Smith&Wesson // Ampersand (& is not a valid character for variable names. In instances in which you want to declare a variable and initialize it, but without giving it any particular value, you may assign it a special value, null. var zaz = null;If you declare a variable without assigning any value to it, it exists but is undefined. var godot;You can declare a variable implicitly (without using var) by assigning a value to it. You cannot, however, use a variable that has never been declared at all. To do so generates an error at runtime. lel = ""; // The variable lel is declared implicitly.Coercion As JScript is a loosely-typed language, variables in JScript technically have no fixed type. Instead, they have a type equivalent to the type of the value they contain. It is possible, under some circumstances, to force the automatic conversion (or coercion) of a variable or a piece of data into a different type. Numbers can easily be included in strings, but strings cannot be included directly in numbers, so explicit conversion functions, parseInt() and parseFloat(), are provided. var theFrom = 1;After this code is executed, the doWhat variable contains "Count from 1 to 10." The number data have been coerced into string form. var nowWhat = 0;After this code is executed, the nowWhat variable contains "0110". The following steps are followed to arrive at this result: Look at the types of 1 and "10". The "10" is a string, the 1 is a number, so the number is coerced into a string. As the values on either side of the + operator are both strings, do a string concatenation. This results in "110" Look at the types of the values on either side of the +=. nowWhat contains a number, and "110" is a string, so convert the number to a string. As there are now strings on either side of the += operator, do a string concatentation. This results in "0110". Store this result in nowWhat. var nowThen = 0; After this code is executed, the nowThen variable contains the integer 11. |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by segsalerty(m): 9:45am On Jun 04, 2009 |
interesting! |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 5:37pm On Jun 06, 2009 |
Preliminary stuffs really, i have not exactly started, this one is still the bread and butter of javascript. No questions yet. . .all is clear then, i have prepared the entire stuff on my pc, am in a cafe now, will continue soonest, by wonder most likely |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by segsalerty(m): 9:39pm On Jun 06, 2009 |
Yeah , waiting for them to come sir, wanna see the , themain themain ! sure , no question so far for what you've posted |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 4:05pm On Jun 07, 2009 |
Javascript Data Types JScript has six types of data. The main types are numbers, strings, objects, and Booleans. The other two are null and undefined. String Data Type Strings are delineated by single or double quotation marks. (Use single quotes to type strings that contain quotation marks.) A string is also an object in JScript, but it is a special case, with special properties. The following are examples of strings: "The cow jumped over the moon." '"Avast, ye lubbers!" roared the technician.' "42" A string can contain zero or more unicode characters. When it contains zero, it is called a zero-length string ("". Number Data Type JScript supports both integer and floating-point numbers. Integers can be positive, 0, or negative; a floating-point number can contain either a decimal point, an "e" (uppercase or lowercase), which is used to represent "ten to the power of" in scientific notation, or both. These numbers follow the IEEE 754 standard for numerical representation. Last, there are certain number values that are special: NaN, or not a Number Positive Infinity Negative Infinity Positive 0 Negative 0 Integers can be represented in base 10 (decimal), base 8 (octal), and base 16 (hexadecimal). Octal integers are specified by a leading "0", and can contain digits 0 through 7. If a number has a leading "0" but contains the digits "8" and/or "9", it is a decimal number. A number that would otherwise be an octal number but contains the letter "e" (or "E" generates an error. Hexadecimal ("hex" integers are specified by a leading "0x" (the "X" can be uppercase or lowercase) and can contain digits 0 through 9 and letters A through F (either uppercase or lowercase). The letter "e" is a permissible digit in hexadecimal notation and does not signify an exponential number. The letters A through F are used to represent, as single digits, the numbers that are 10 through 15 in base 10. That is, 0xF is equivalent to 15, and 0x10 is equivalent to 16. Octal and hexadecimal numbers can be negative, but cannot be fractional. A number that begins with a single "0" and contains a decimal point is a decimal floating-point number; if a number that begins with "0x" or "00" contains a decimal point, anything to the right of the decimal point is ignored. Some example numbers: .0001, 0.0001, 1e-4, 1.0e-4 // Four floating-point numbers, equivalent to each other. 3.45e2 // A floating-point number, equivalent to 345. 42 // An integer number. 0377 // An octal integer, equivalent to 255. 00.0001 // As octal numbers cannot have decimal parts, this is equivalent to 0. 0378 // An integer, equivalent to 378. 0Xff // A hexadecimal integer, equivalent to 255. 0x37CF // A hexadecimal integer, equivalent to 14287. 0x3e7 // A hexadecimal integer, equivalent to 999. 0x3.45e2 // As hexadecimal numbers cannot have decimal parts, this is equivalent to 3. Booleans The possible Boolean values are true and false. These are special values, and are not usable as 1 and 0. Note In a comparison, any expression that evaluates to 0 is taken to be false, and any statement that evaluates to a number other than 0 is taken to be true. Thus the following expression evaluates to true: (false == 0) For more information on comparisons, see Controlling Program Flow. Undefined Data Type A value that is undefined is simply a value given to a variable after it has been created, but before a value has been assigned to it. Null Data Type A null value is one that has no value and means nothing. |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 4:08pm On Jun 07, 2009 |
JScript Operators JScript has a full range of operators, including arithmetic, logical, bitwise, and assignment operators. There are also a few miscellaneous operators. Operator Precedence Operators in JScript are evaluated in a particular order. This order is known as the operator precedence. The following table lists the operators in highest to lowest precedence order. Operators in the same row are evaluated in left to right order. Operator Description . [] () Field access, array indexing, and function calls ++ -- - ~ ! typeof new void delete Unary operators, return data type, object creation, undefined values * / % Multiplication, division, modulo division + - + Addition, subtraction, string concatenation << >> >>> Bit shifting < <= > >= Less than, less than or equal to, greater than, greater than or equal to == != === !== Equality, inequality, identity, nonidentity & Bitwise AND ^ Bitwise XOR | Bitwise OR && Logical AND || Logical OR ?: Conditional = OP= Assignment, assignment with operation , Multiple evaluation Parentheses are used to alter the order of evaluation. The expression within parentheses is fully evaluated before its value is used in the remainder of the statement. An operator with higher precedence is evaluated before one with lower precedence. For example: z = 78 * (96 + 3 + 45) There are five operators in this expression: =, *, (), +, and +. According to precedence, they are evaluated in the following order: (), *, +, +, =. Evaluation of the expression within the parentheses is first: There are two addition operators, and they have the same precedence: 96 and 3 are added together and 45 is added to that total, resulting in a value of 144. Multiplication is next: 78 and 144 are multiplied, resulting in a value of 11232. Assignment is last: 11232 is assigned into z. |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 4:24pm On Jun 07, 2009 |
I am still on basic javascript, questions will be answered as usual, now i am wondering if i am going too fast or too slow, but as i am not getting any response, so i guess i should just keep moving. Controlling Program Flow Now this is a very serious business especially for beginners. 'cos though it is basic, but if you fail to understand this bit you can never be a programmer in any language. . . Why Control the Flow of Execution? Fairly often, you need a script to do different things under different conditions. For example, you might write a script that checks the time every hour, and changes some parameter appropriately during the course of the day. You might write a script that can accept some sort of input, and act accordingly. Or you might write a script that repeats a specified action. There are several kinds of conditions that you can test. All conditional tests in Microsoft JScript are Boolean, so the result of any test is either true or false. You can freely test values that are of Boolean, numeric, or string type. JScript provides control structures for a range of possibilities. The simplest control structures are the conditional statements. Using Conditional Statements JScript supports if and if, else conditional statements. In if statements a condition is tested, and if the condition meets the test, some JScript code you've written is executed. (In the if, else statement, different code is executed if the condition fails the test.) The simplest form of an if statement can be written entirely on one line, but multiline if and if, else statements are much more common. The following examples demonstrate syntaxes you can use with if and if, else statements. The first example shows the simplest kind of Boolean test. If (and only if) the item between the parentheses evaluates to true, the statement or block of statements after the if is executed. // The smash() function is defined elsewhere in the code. Conditional Operator JScript also supports an implicit conditional form. It uses a question mark after the condition to be tested (rather than the word if before the condition), and specifies two alternatives, one to be used if the condition is met and one if it is not. The alternatives are separated by a colon. var hours = ""; // Code specifying that hours contains either the contents of // theHour, or theHour - 12. hours += (theHour >= 12) ? " PM" : " AM"; -------------------------------------------------------------------------------- Tip If you have several conditions to be tested together, and you know that one is more likely to pass or fail than any of the others, depending on whether the tests are connected with OR (||) or AND (&&, you can speed execution of your script by putting that condition first in the conditional statement. For example, if three conditions must all be true (using && operators) and the second test fails, the third condition is not tested. Similarly, if only one of several conditions must be true (using || operators), testing stops as soon as any one condition passes the test. This is particularly effective if the conditions to be tested involve execution of function calls or other code. An example of the side effect of short-circuiting is that runsecond will not be executed in the following example if runfirst() returns 0 or false. if ((runfirst() == 0) || (runsecond() == 0)) Using Repetition, or Loops There are several ways to execute a statement or block of statements repeatedly. In general, repetitive execution is called looping. It is typically controlled by a test of some variable, the value of which is changed each time the loop is executed. Microsoft JScript supports many types of loops: for loops, for, in loops, while loops, do, while loops, and switch loops. Using for Loops The for statement specifies a counter variable, a test condition, and an action that updates the counter. Just before each time the loop is executed (this is called one pass or one iteration of the loop), the condition is tested. After the loop is executed, the counter variable is updated before the next iteration begins. If the condition for looping is never met, the loop is never executed at all. If the test condition is always met, an infinite loop results. While the former may be desirable in certain cases, the latter rarely is, so take care when writing your loop conditions. /* Using for, in Loops JScript provides a special kind of loop for stepping through all the properties of an object. The loop counter in a for, in loop steps through all indexes in the array. It is a string, not a number. for (j in tagliatelleVerde) // tagliatelleVerde is an object with several properties Using while Loops The while loop is very similar to a for loop. The difference is that a while loop does not have a built-in counter variable or update expression. If you already have some changing condition that is reflected in the value assigned to a variable, and you want to use it to control repetitive execution of a statement or block of statements, use a while loop. var theMoments = ""; -------------------------------------------------------------------------------- Note Because while loops do not have explicit built-in counter variables, they are even more vulnerable to infinite looping than the other types. Moreover, partly because it is not necessarily easy to discover where or when the loop condition is updated, it is only too easy to write a while loop in which the condition, in fact, never does get updated. You should be extremely careful when you design while loops. Using break and continue Statements JScript provides a statement to stop the execution of a loop. The break statement can be used to stop execution if some (presumably special) condition is met. The continue statement can be used to jump immediately to the next iteration, skipping the rest of the code block but updating the counter variable as usual if the loop is a for or for, in loop. var theComment = ""; |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 5:16pm On Jun 07, 2009 |
JScript Functions There is something else you must keep in mind, that despite the fact that i am using microsoft javascript as my standard here, the actual codes i am going to be posting apply to other platforms and other browsers. What Is a Function? JScript functions perform actions. They can also return results. Sometimes these are the results of calculations or comparisons. Functions combine several operations under one name. This lets you streamline your code. You can write out a set of statements, name it, and then execute the entire set any time you want to, just by calling it and passing to it any information it needs. You pass information to a function by enclosing the information in parentheses after the name of the function. Pieces of information that are being passed to a function are called arguments or parameters. Some functions don't take any arguments at all; some functions take one argument; some take several. There are even functions for which the number of arguments depends on how you are using the function. JScript supports two kinds of functions: those that are built into the language, and those you create yourself. Special Built-in Functions The JScript language includes several built-in functions. Some of them let you handle expressions and special characters, and convert strings to numeric values. For example, escape() and unescape() are used to convert characters that have special meanings in HTML code, characters that you cannot just put directly into text. For example, the angle brackets, "<" and ">", delineate HTML tags. The escape function takes as its argument any of these special characters, and returns the escape code for the character. Each escape code consists of a percent sign (%) followed by a two-digit number. The unescape function is the exact inverse. It takes as its argument a string consisting of a percent sign and a two-digit number, and returns a character. Another useful built-in function is eval(), which evaluates any valid mathematical expression that is presented in string form. The eval() function takes one argument, the expression to be evaluated. var anExpression = "6 * 9 % 7";Consult the language reference for more information about these and other built-in functions. Creating Your Own Functions You can create your own functions and use them where you need them. A function definition consists of a function statement and a block of JScript statements. The checkTriplet function in the following example takes as its arguments the lengths of the sides of a triangle, and calculates from them whether the triangle is a right triangle by checking whether the three numbers constitute a Pythagorean triplet. (The square of the length of the hypotenuse of a right triangle is equal to the sum of the squares of the lengths of the other two sides.) The checkTriplet function calls one of two other functions to make the actual test. Notice the use of a very small number ("epsilon" as a testing variable in the floating-point version of the test. Because of uncertainties and roundoff errors in floating-point calculations, it is not practical to make a direct test of whether the square of the hypotenuse is equal to the sum of the squares of the other two sides unless all three values in question are known to be integers. Because a direct test is more accurate, the code in this example determines whether it is appropriate and, if it is, uses it. var epsilon = 0.0000000000001; // Some very small number to test against. |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by segsalerty(m): 11:09pm On Jun 07, 2009 |
Nice , gone far but i am still meeting up ! Thumbs up Sir! |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 2:25am On Jun 08, 2009 |
Aaaand that ends the basic javascript, now i will be moving to advanced javascript [still on the javascript language], before getting down to the real business of why we are here, to learn how to combine javascript with html, css, php in short, how to take it to (dynamic html programming) dhtml. |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 4:05am On Jun 08, 2009 |
Recursion Recursion is an important programming technique. It's used to have a function call itself from within itself. One handy example is the calculation of factorials. The factorials of 0 and 1 are both defined specifically to be 1. The factorials of larger numbers are calculated by multiplying 1 * 2 * , , incrementing by 1 until you reach the number for which you're calculating the factorial. The following paragraph is a function, defined in words, that calculates a factorial. "If the number is less than zero, reject it. If it isn't an integer, round it down to the next integer. If the number is zero or one, its factorial is one. If the number is larger than one, multiply it by the factorial of the next smaller number." To calculate the factorial of any number that is larger than 1, you need to calculate the factorial of at least one other number. The function you use to do that is the function you're in the middle of already; the function must call itself for the next smaller number, before it can execute on the current number. This is an example of recursion. Clearly, there is a way to get in trouble here. You can easily create a recursive function that doesn't ever get to a definite result, and cannot reach an endpoint. Such a recursion causes the computer to execute a so-called "infinite" loop. Here's an example: omit the first rule (the one about negative numbers) from the verbal description of calculating a factorial, and try to calculate the factorial of any negative number. This fails, because in order to calculate the factorial of, say, -24 you first have to calculate the factorial of -25; but in order to do that you first have to calculate the factorial of -26; and so on. Obviously, this never reaches a stopping place. Thus, it is extremely important to design recursive functions with great care. If you even suspect that there's any chance of an infinite recursion, you can have the function count the number of times it calls itself. If the function calls itself too many times, however many you decide that should be, it automatically quits. Here's the factorial function again, this time written in JScript code. function factorial(aNumber) { aNumber = Math.floor(aNumber); // If the number is not an integer, round it down. if (aNumber < 0) { // If the number is less than zero, reject it. return "not a defined quantity"; } if ((anumber == 0) || (anumber == 1)) { // If the number is 0 or 1, its factorial is 1. return 1; } else return (anumber * factorial(anumber - 1)); // Otherwise, recurse until done. } |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 4:06am On Jun 08, 2009 |
Variable Scope Microsoft JScript has two scopes: global and local. If you declare a variable outside of any function definition, it is a global variable, and its value is accessible and modifiable throughout your program. If you declare a variable inside of a function definition, that variable is local. It is created and destroyed every time the function is executed; it cannot be accessed by anything outside the function. A local variable can have the same name as a global variable, but it is entirely distinct and separate. Consequently, changing the value of one variable has no effect on the other. Inside the function in which the local variable is declared, only the local version has meaning. var aCentaur = "a horse with rider,"; // Global definition of aCentaur. // JScript code, omitted for brevity. function antiquities() // A local aCentaur variable is declared in this function. { // JScript code, omitted for brevity. var aCentaur = "A centaur is probably a mounted Scythian warrior"; // JScript code, omitted for brevity. aCentaur += ", misreported; that is, "; // Adds to the local variable. // JScript code, omitted for brevity. } // End of the function. var nothinginparticular = antiquities(); aCentaur += " as seen from a distance by a naive innocent."; /* Within the function, the variable contains "A centaur is probably a mounted Scythian warrior, misreported; that is, "; outside the function, the variable contains the rest of the sentence: "a horse with rider, as seen from a distance by a naive innocent." */ It's important to note that variables act as if they were declared at the beginning of whatever scope they exist in. Sometimes this results in unexpected behaviors. var aNumber = 100;The statement that is commented out attempts to assign the value of the local variable aNumber to the local variable newThing. It fails, despite the fact that a local aNumber variable is defined elsewhere in the function, and therefore exists throughout. The aNumber variable does not have any assigned value at the point where this statement occurs in the code, and is thus undefined. |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 5:09am On Jun 08, 2009 |
Using Arrays Array Indexing Arrays in JScript are sparse. That is, if you have an array with three elements that are numbered 0, 1, and 2, you can create element 50 without worrying about elements 3 through 49. If the array has an automatic length variable (see Intrinsic Objects for an explanation of automatic monitoring of array length), the length variable is set to 51, rather than to 4. You can certainly create arrays in which there are no gaps in the numbering of elements, but you aren't required to. In fact, in JScript, your arrays don't have to have numbered subscripts at all. In JScript, objects and arrays are essentially identical to each other. The real difference is not in the data, but rather in the way you address the members of an array or the properties and methods of an object. Addressing Arrays There are two main ways to address the members of an array. Ordinarily, you address arrays by using brackets. The brackets enclose either a numeric value or an expression that evaluates to a nonnegative integer. The following example assumes that the entryNum variable is defined and assigned a value elsewhere in the script. theListing = addressBook[entryNum]; theFirstLine = theListing[1]; This method of addressing is equivalent to the method for addressing objects, though in object addressing, what follows the period must be the name of an actual property. If there is no such property, your code generates an error. The second way to address an array is to make an object/array that contains properties that are numbered, and then generate the numbers in a loop. The following example generates two arrays, one for the name and one for the address, from a listing in addressBook. Each of these contains four properties. An instance of theName, for example, built from the [Name1] through [Name4] properties of theListing, might contain "G." "Edward" "Heatherington" "IV", or "George" "" "Sand" "". theListing = addressBook[entryNum]; for (i = 1; i < 4; i++) { theName[i] = theListing["Name" + i]; theAddress[i] = theListing["Address" + i]; } While this particular instance is short, and could easily have been written in the "dot" style of notation, (that is, addressing theListing, theName, and theAddress as objects rather than as arrays), that is not always possible. Sometimes the particular property may not exist until run time, or there may be no way to know which one it will be in advance. For example, if the addressBook array were arranged by last name instead of by numbered listings, the user would probably be entering names "on the fly," while the script is running, to look people up. The following example assumes the existence of appropriate function definitions elsewhere in the script. theListing = addressBook[getName()]; theIndivListing = theListing[getFirstName()]; This is associative addressing of the array, that is, addressing by means of fully arbitrary strings. Objects in JScript are actually associative arrays. Although you can (and frequently do) use the "dot" style of addressing, you are not by any means required to. Because the members of any JScript object can be accessed using array notation, a JScript object can be used as an associative array. The following code creates and initializes the most familiar form of an array: var myArray = new Array("Athens", "Belgrade", "Cairo" Each element of this array is addressed using its element number; in this case 0, 1, or 2. Using the for, in statement, the array can be iterated starting at 0 and ending at 2. For example: for (key in myArray) document.write("Element value is " + MyArray[key] + "<BR> The following code creates and initializes an associative array containing three elements: var MyArray = {"a" : "Athens", "b" : "Belgrade", "c" : "Cairo" }; In this array, elements are addressed using the key strings("a", "b", or "c" instead of an array element number (0, 1, or 2). This allows you to create and use arrays with more intuitive addressing schemes. The same for, in statement code shown above can be used to iterate this array as well. |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 5:12am On Jun 08, 2009 |
Advanced Object Creation Using Constructors to Create Objects In Microsoft JScript, you use constructors to create and build a class of objects. You invoke a constructor with the new statement. It returns whatever it constructs. The special case Function constructor lets you create functions that are anonymous. An anonymous function is one that does not have a name. You can use the Function constructor to build a function "on the fly", for example, as one of the instructions inside another function. Such a function, which is only called from the one location, doesn't need a name. In the following example, such an anonymous function generates one line of a "name-and-email-address" listing. It checks the value of the firstNameFirst variable to decide whether to put the first name or the last name first, and the value of the emailNameFirst variable to decide whether to put the name or the email address first. The example assumes that the values of firstNameFirst and emailNameFirst are set elsewhere. for (j = 1; j < addressList[length]; j++)Writing Constructors To write your own constructors, you use the this keyword within the constructor to refer to the newly-created object. The constructor initializes the object. Though the constructor in the next example starts at an index of 0, this is not required. You can start with a first index of 1 if, for example, you want a parameter that indicates the actual number of indexes of the array or object. In the example, it's called extent to distinguish it from the automatically maintained length parameter of the built-in Array( ) object). If you write code that adds properties to the array, you have to update the extent parameter (or your equivalent) because this parameter is not maintained by JScript. Notice that even this extremely simple example uses both object (dot) and array (bracket) notation styles to refer to the current object. function MakeStringArray(length) {Using Prototypes to Create Objects When you write an object definition, you can use prototype properties to create properties that are held in common by all objects that are generated by the definition. Prototype properties are copied by reference into each object of a class, so they have the same value for all objects in the class. However, you can change the value of a prototype property in one object, and the new value overrides the default, but only in that one instance. Other objects that are members of the class are not affected by the change. Using this principle, you can define additional properties for objects that are part of the JScript language, which all have prototypes. For example, if you want a special constant for a calculation, and the constant is not among those provided in the Math and Number objects, you can define it yourself and then assign it their respective object prototypes, or the prototype property of your object class. Math.prototype.Avogadro = 6.0232E23; function howManyMolecules(wtGrams,molWt) { return ((wtGrams/molWt)*Math.prototype.Avogadro); } document.write("There are " + howManyMolecules(window.prompt("How many grams?",0),window.prompt ("What's the molecular weight?",0)) + " molecules in that amount." Perhaps more to the point, you can define a function, assign it to String.prototype as a method, and use it on any string anywhere in your script. The following example assumes the existence of a Periodic Chart array called "theElements", defined elsewhere in the script, which contains symbols for the elements, their names, their atomic weights, and other relevant information about them. decodeFormula(window.prompt("Formula?","Al2O3"); |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 5:14am On Jun 08, 2009 |
Special Characters Special Characters JScript provides special characters that allow you to include in strings some characters you can't type directly. Each of these characters begins with a backslash. The backslash is an escape character you use to inform the JScript interpreter that the next character is special. Escape Sequence Character \b Backspace \f Form feed \n Line feed (newline) \r Carriage return \t Horizontal tab (Ctrl-I) \' Single quotation mark \" Double quotation mark \\ Backslash Notice that because the backslash itself is used as the escape character, you cannot directly type one in your script. If you want to write a backslash, you must type two of them together (\\). document.write('The image path is C:\\webstuff\\mypage\\gifs\\garden.gif.');You can use these escape sequences to control formatting of text inside <PRE> and <XMP> tags and, to some extent, inside alert, prompt, and confirm message boxes. |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 6:10am On Jun 08, 2009 |
Troubleshooting Your Scripts There are places in any programming language where you can get caught if you are not careful, and every language has specific surprises in it. Take, for example, the null value: The one in Microsoft JScript behaves differently than the null value in the C or C++ languages. Here are some of the trouble areas that that you may run into as you write JScript scripts. Syntax Errors Because syntax is much more rigid in programming languages than in natural languages, it is important to pay strict attention to detail when you write scripts. If, for example, you mean for a particular parameter to be a string, you will run into trouble if you forget to enclose it in quotation marks when you type it. Order of Script Interpretation JScript interpretation is part of the your Web browser's HTML parsing process. So, if you place a script inside the <HEAD> tag in a document, it is interpreted before any of the <BODY> tag is examined. If you have objects that are created in the <BODY> tag, they do not exist at the time the <HEAD> is being parsed, and cannot be manipulated by the script. Automatic Type Coercion JScript is a loosely typed language with automatic coercion. Consequently, despite the fact that values having different types are not equal, the expressions in the following example evaluate to true. "100" == 100 false == 0 Operator Precedence When a particular operation is performed during the evaluation of an expression has more to do with operator precedence than with the location of the expression. Thus, in the following example, multiplication is performed before subtraction, even though the subtraction appears first in the expression. theRadius = aPerimeterPoint - theCenterpoint * theCorrectionFactor; Using for, in Loops with Objects When you step through the properties of an object with a for, in loop, you cannot necessarily predict or control the order in which the fields of the object are assigned to the loop counter variable. Moreover, the order may be different in different implementations of the language. with Keyword The with statement is convenient for addressing properties that already exist in a specified object, but cannot be used to add properties to an object. To create new properties in an object, you must refer to the object specifically. this Keyword Although you use the this keyword inside the definition of an object, to refer to the object itself, you cannot ordinarily use this or similar keywords to refer to the currently executing function when that function is not an object definition. You can, if the function is to be assigned to an object as a method, use the this keyword within the function, to refer to the object. Writing a Script That Writes a Script The </SCRIPT> tag terminates the current script if the interpreter encounters it. To display "</SCRIPT>" itself, rewrite this as at least two strings, for example, "</SCR" and "IPT>", which you can then concatenate together in the statement that writes them out. Implicit Window References Because more than one window can be open at a time, any window reference that is implicit is taken to point to the current window. For other windows, you must use an explicit reference. |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 6:13am On Jun 08, 2009 |
Aaaand dat ends my tutorial on the javascript language. That was rather fast, but time waits for no man. So now, i am going to move to browser objects and how to manipulate them with javascript. This one is going to be more interesting than the other ones! |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by segsalerty(m): 9:07am On Jun 08, 2009 |
Yeah , thanks siir ooo' i cant wait for themain themain i still dey gradb what you've thought so far |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 8:07pm On Jun 08, 2009 |
Iight man, i will continue later tonight. I am wondering where the rest of the students are, segsalert are you the only one in the class? anyways, they will come and read up later on! |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by quadrillio(m): 10:07am On Jun 09, 2009 |
dhtml: DHTML, I've Joined the class ooo, segsalert u are not alone. lol |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 10:09am On Jun 09, 2009 |
Hey what are you doing here? you are supposed to be assisting me, not segsalert!! |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 10:33am On Jun 09, 2009 |
Now i am going to introduce y'all to browser objects - the elements in the browser that javascript can control / manipulate: ADDRESS APPLET AREA B BASE BASEFONT BGSOUND BIG BLOCKQUOTE BODY BUTTON CAPTION CENTER currentStyle DIV DL document DT EM EMBED event external FIELDSET FONT FORM FRAME FRAMESET HEAD Hn HR IFRAME IMG INPUT INS ISINDEX KBD LABEL LEGEND LI LINK location NOSCRIPT OBJECT OL OPTION P TABLE TBODY TD TEXTAREA VAR WBR window XML All the tags you can think of in HTML can be considered as objects in short. |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 10:37am On Jun 09, 2009 |
These objects are arranged in a hierarchy, as in from top to bottom. . . i wish i could draw a graphic at this point. K, i will pause this thread to draw the graphical stuff later, it can not be visualized easily with words. But the lesson here is that the topmost object in a web browser is the window object, so to change title can be window.document.title="Welcome to my world"; To be continued. . . . |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 12:42pm On Jun 10, 2009 |
I forgot to draw cross lines between them. So as i was sayin the window object is the topmost object. Other objects are inherited from it like the document object, alert, setTimeout and several other objects like that. Dont bother if you do not understand the last 2 posts, but read them all the same, as we go on it will get clearer. To be continued. . .i need a bottle of coca cola
|
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by segsalerty(m): 9:44pm On Jun 10, 2009 |
Uhmm , class is getting really interesting , pls carry on ! |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 10:10pm On Jun 10, 2009 |
Iight, be back later, have some little work to do somewhere else other than NL. . . . |
Re: Javascript Tutorial For Newbies [both Procedural / Oop Inclusive] by Nobody: 10:24pm On Jun 11, 2009 |
Assigment, i need to talk about some objects, their properties, methods, events and event handlers. Now i need one of the students to do a little homework on what objects are, and also talk about properties, methods and events. . . of objects. . . aaaaaaaand post it here, before i continue. |
Let us hold a web designers Fair in Lagos ? / I Need Serious Help With Whogohost / Sendblaster Pro 4 Licence Key
(Go Up)
Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health religion celebs tv-movies music-radio literature webmasters programming techmarket Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10) Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 175 |