La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

 2008 Pearson Education, Inc. All rights reserved. 1 6 6 JavaScript: Introduction to Scripting.

Presentaciones similares


Presentación del tema: " 2008 Pearson Education, Inc. All rights reserved. 1 6 6 JavaScript: Introduction to Scripting."— Transcripción de la presentación:

1  2008 Pearson Education, Inc. All rights reserved. 1 6 6 JavaScript: Introduction to Scripting

2  2008 Pearson Education, Inc. All rights reserved. 2 OBJECTIVES  En este capítulo aprenderemos como: –Escribir programas simples en JavaScript. –Utilizar declaraciones de input y output. –Comprender conceptos básicos de memoria. –Utilizar operadores matemáticos. –Comprende la precedencia de los operadores matemáticos. –Poder escribir declaraciones de toma de desiciones (IF). –Poder utilizar operadores relacionales y de igualdad.

3  2008 Pearson Education, Inc. All rights reserved. 3 6.1Introduction 6.2 Simple Program: Displaying a Line of Text in a Web Page 6.3 Modifying Our First Program 6.4 Obtaining User Input with prompt Dialogs 6.5 Memory Concepts 6.6 Arithmetic 6.7 Decision Making: Equality and Relational Operators 6.8 Wrap-Up 6.9 Web Resources

4  2008 Pearson Education, Inc. All rights reserved. 4 6.1 Introduction JavaScript scripting language – Mejora la funcionalidad y apariencia – Código que se ejecuta a nivel del cliente Hace que las páginas sean mas dinámicas e interactivas – Provee fundamentos para scripts más complejos a nivel de servidor Antes de correr ejemplos de códigos con JavaScript en la computadora, necesitamos cambiar los parámetros de seguridad del browser. – IE7 previene que or default se corran los scripts – FF2 Lo permite por default

5  2008 Pearson Education, Inc. All rights reserved. 5 Fig. 6.1 | Enabling JavaScript in Internet Explorer 7

6  2008 Pearson Education, Inc. All rights reserved. 6 6.2 Simple Program: Displaying a Line of Text in a Web Page Inline scripting – Javascript se escribe en el elemento del documento – Utiliza el tag: Indica que el texto es parte del script atributo type – Especifica el tipo de archivo y el lenguaje a utilizar metodo writeln – Escribe una línea en el documento Escape character ( \ ) – Indica un caracter especial dentro de un string metodo alert – Caja de dialogo (Dialog box)

7  2008 Pearson Education, Inc. All rights reserved. 7 Portability Tip 6.1 Some browsers do not support the tags. If your document is to be rendered with such browsers, enclose the script code between these tags in an XHTML comment, so that the script text does not get displayed as part of the web page. The closing comment tag of the XHTML comment ( --> ) is preceded by a JavaScript comment ( // ) to prevent the browser from trying to interpret the XHTML comment as a JavaScript statement.

8  2008 Pearson Education, Inc. All rights reserved. 8 Common Programming Error 6.1 Forgetting the ending tag for a script may prevent the browser from interpreting the script properly and may prevent the XHTML document from loading properly.

9  2008 Pearson Education, Inc. All rights reserved. 9 Software Engineering Observation 6.1 Strings in JavaScript can be enclosed in either double quotation marks ( " ) or single quotation marks ( ' ).

10  2008 Pearson Education, Inc. All rights reserved. 10 Good Programming Practice 6.1 Always include a semicolon at the end of a statement to terminate the statement. This notation clarifies where one statement ends and the next statement begins.

11  2008 Pearson Education, Inc. All rights reserved. 11 Common Programming Error 6.2 JavaScript is case sensitive. Not using the proper uppercase and lowercase letters is a syntax error. A syntax error occurs when the script interpreter cannot recognize a statement. The interpreter normally issues an error message to help you locate and fix the incorrect statement. Syntax errors are violations of the rules of the programming language. The interpreter notifies you of a syntax error when it attempts to execute the statement containing the error. The JavaScript interpreter in Internet Explorer reports all syntax errors by indicating in a separate popup window that a “runtime error” has occurred (i.e., a problem occurred while the interpreter was running the script). [Note: To enable this feature in IE7, select Internet Options from the Tools menu. In the Internet Options dialog that appears, select the Advanced tab and click the checkbox labelled Display a notification about every script error under the Browsing category. Firefox has an error console that reports JavaScript errors and warnings. It is accessible by choosing Error Console from the Tools menu.]

12  2008 Pearson Education, Inc. All rights reserved. 12 6.2 Simple Program: Displaying a Line of Text in a Web Page (Cont.) The document object’s writeln method – Writes a line of XHTML text in the XHTML document – Does not guarantee that a corresponding line of text will appear in the XHTML document. – Text displayed is dependent on the contents of the string written, which is subsequently rendered by the browser. – Browser will interpret the XHTML elements as it normally does to render the final text in the document

13  2008 Pearson Education, Inc. All rights reserved. 13 Fig. 6.2 | Displaying a line of text. Script begins Prevents older browsers that do not support scripting from displaying the text of the script XHTML comment delimiter, commented for correct interpretation by all browsers Script ends Aquí se declara que el código que viene es de Javascript. Clase: Documento, Método: writeln

14  2008 Pearson Education, Inc. All rights reserved. 14 Error-Prevention Tip 6.1 When the interpreter reports a syntax error, sometimes the error is not on the line number indicated by the error message. First, check the line for which the error was reported. If that line does not contain errors, check the preceding several lines in the script.

15  2008 Pearson Education, Inc. All rights reserved. 15 6.3 Modifying Our First Program El método write muestra un string en pantalla al igual que el writeln, pero no posiciona el cursor al principio de la próxima línea, sino que se queda al final del texto. No se puede separar un enunciado a mitad de un string. El operador + (operador de concadenación) cuando se utiliza de esta manera, te una dos cadenas de caracteres.

16  2008 Pearson Education, Inc. All rights reserved. 16 Common Programming Error 6.3 Splitting a statement in the middle of a string is a syntax error.

17  2008 Pearson Education, Inc. All rights reserved. 17 Fig. 6.3 | Printing one line with separate statements. Two write statements create one line of XHTML text Concatenation operator joins the string together, as it is split into multiple lines Aquí se escribe el mensaje anterior con color magneta

18  2008 Pearson Education, Inc. All rights reserved. 18 6.3 Modifying Our First Program (Cont.) Un enunciado sencillo puede hacer que el browser muestre múltiples líneas al utilizar el tag

19  2008 Pearson Education, Inc. All rights reserved. 19 Fig. 6.4 | Printing on multiple lines with a single statement. Inserts line-break Aquí se escribe el mensaje anterior en tres líneas separadas.

20  2008 Pearson Education, Inc. All rights reserved. 20 6.3 Modifying Our First Program (Cont.) Dialogs – Son útiles para mostrar información en ventanas que aparecen (“pop up”) en la pantalla para atraer la atención del usuario. – Típicamente se utilizan para mostrar mensajes importantes al usuario. – El objeto window utiliza el método alert para mostrar un alert dialog – El método alert requiere como argumento, el string que va a ser mostrado.

21  2008 Pearson Education, Inc. All rights reserved. 21 Fig. 6.5 | Alert dialog displaying multiple lines. Creates a pop up box that alerts the welcome text to the user Aquí se escribe el mensaje anterior en una ventana de alerta. Este mensaje sale en la página del browser. Dar Refresh hace que el código se ejecute de nuevo.

22  2008 Pearson Education, Inc. All rights reserved. 22 Common Programming Error 6.5 Dialogs display plain text; they do not render XHTML. Therefore, specifying XHTML elements as part of a string to be displayed in a dialog results in the actual characters of the tags being displayed.

23  2008 Pearson Education, Inc. All rights reserved. 23 Common Programming Error 6.6 XHTML elements in an alert dialog’s message are not interpreted as XHTML.This means that using, for example, to create a line break in an alert box is an error. The string will simply be included in your message.

24  2008 Pearson Education, Inc. All rights reserved. 24 Fig. 6.6 | Some common escape sequences.

25  2008 Pearson Education, Inc. All rights reserved. 25 Good Programming Practice 6.2 Choosing meaningful variable names helps a script to be “self-documenting” (i.e., easy to understand by simply reading the script, rather than having to read manuals or extended comments).

26  2008 Pearson Education, Inc. All rights reserved. 26 Good Programming Practice 6.3 By convention, variable-name identifiers begin with a lowercase first letter. Each subsequent word should begin with a capital first letter. For example, identifier itemPrice has a capital P in its second word, Price.

27  2008 Pearson Education, Inc. All rights reserved. 27 Common Programming Error 6.7 Splitting a statement in the middle of an identifier is a syntax error.

28  2008 Pearson Education, Inc. All rights reserved. 28 Good Programming Practice 6.4 Some programmers prefer to declare each variable on a separate line. This format allows for easy insertion of a descriptive comment next to each declaration. This is a widely followed professional coding standard.

29  2008 Pearson Education, Inc. All rights reserved. 29 Common Programming Error 6.8 Forgetting one of the delimiters of a multiline comment is a syntax error.

30  2008 Pearson Education, Inc. All rights reserved. 30 Common Programming Error 6.9 Nesting multiline comments (i.e., placing a multiline comment between the delimiters of another multiline comment) is a syntax error.

31  2008 Pearson Education, Inc. All rights reserved. 31 6.4 Obtaining User Input with prompt Dialogs (Cont.) EL método propmt del objeto window muestra una caja de dialogo en donde el usuario puede entrar un valor. – El primer argumento es el mensaje (prompt) Que le indica al usuario cual es el valor que debe entrar – El segundo argumento opcional es un valor default que el programa asume si el usuario no entra nada. El Script puede entonces utilizar el valor suministrado por el usuario. Esto añade el elemento de interactividad a las páginas.

32  2008 Pearson Education, Inc. All rights reserved. 32 Good Programming Practice 6.5 Place spaces on either side of a binary operator. This format makes the operator stand out and makes the program more readable.

33  2008 Pearson Education, Inc. All rights reserved. 33 Common Programming Error 6.10 Confusing the + operator used for string concatenation with the + operator used for addition often leads to undesired results. For example, if integer variable y has the value 5, the expression "y + 2 = " + y + 2 results in "y + 2 = 52", not "y + 2 = 7", because first the value of y (i.e., 5) is concatenated with the string "y + 2 = ", then the value 2 is concatenated with the new, larger string "y + 2 = 5". The expression "y + 2 = " + (y + 2) produces the string "y + 2 = 7" because the parentheses ensure that y + 2 is executed mathematically before it is converted to a string.

34  2008 Pearson Education, Inc. All rights reserved. 34 Fig. 6.7 | Prompt box used on a welcome screen (Part 1 of 2). Declaración de variable. Pide un valor al usuario y lo guarda en la variable name. Escribe un mensaje de saludo utilizando el nombre que escribió el usuario.

35  2008 Pearson Education, Inc. All rights reserved. 35 Fig. 6.7 | Prompt box used on a welcome screen (Part 2 of 2).

36  2008 Pearson Education, Inc. All rights reserved. 7.3.1 Dynamic Welcome Page Fig. 7.7Prompt dialog displayed by the window object’s prompt method. Mensaje que le sale al usuario que le indica lo que debe entrar. Este es el valor default en caso de que el usuario no entre nada. Aquí el usuario entra el dato deseado. Al presionaer el botón de OK, el valor pasa a la variable asignada.

37  2008 Pearson Education, Inc. All rights reserved. 7.3.2 Adding Integers El próximo script pide al usuario dos valores enteros y calcula la suma de ambos – NaN (not a number) – parseInt Convierte el string de un argumento a un entero

38  2008 Pearson Education, Inc. All rights reserved. 38 Fig. 6.9 | Addition script (Part 1 of 2). Assigns the first input from the user to the variable firstNumber Assigns the second input from the user to the variable secondNumber Converts the strings entered by the user into integers Definición de variables. Suma de los dos números.

39  2008 Pearson Education, Inc. All rights reserved. 39 Fig. 6.9 | Addition script (Part 2 of 2). Escribe en la página el resultado.

40  2008 Pearson Education, Inc. All rights reserved. 40 6.5 Memory Concepts Los nombres de variables corresponden a localizaciones en la memoria de la computadora. Cada variable tiene un nombre, su tipo y valor. Cuando un valor se coloca en una localización de memoria, reemplaza el valor que tenía anteriormente. Cuando el valor se lee de una localización de memoria, el proceso no destruye el valor.

41  2008 Pearson Education, Inc. All rights reserved. 41 Fig. 6.10 | Memory location showing the name and value of variable number1.

42  2008 Pearson Education, Inc. All rights reserved. 42 Fig. 6.11 | Memory locations after inputting values for variables number1 and number2.

43  2008 Pearson Education, Inc. All rights reserved. 43 Fig. 6.12 | Memory locations after calculating the sum of number1 and number2.

44  2008 Pearson Education, Inc. All rights reserved. 44 6.5 Memory Concepts (Cont.) JavaScript no requiere que las variables sean de algún tipo antes que el programa las utilize. Una variable puede contener un valor de cualquier tipod e dato. En muchas situaciones Javascript automáticamente convierte entre valores de diferentes tipos. Cuando una variable es declarada, pero no se le asigna un valor, se le asigna un valor no definido (undefined value). – Tratar de utilizar ese valor es un error de lógica. Cuando las variables e declaran, no se le asigna valores defaults a menos que lo especifique el programdor. er. – Para indicr que una variable no contiene un valor, se puede asignar el valor null.

45  2008 Pearson Education, Inc. All rights reserved. 45 Fig. 6.13 | Arithmetic operators.

46  2008 Pearson Education, Inc. All rights reserved. 46 Good Programming Practice 6.6 Using parentheses for complex arithmetic expressions, even when the parentheses are not necessary, can make the arithmetic expressions easier to read.

47  2008 Pearson Education, Inc. All rights reserved. 47 Fig. 6.14 | Precedence of arithmetic operators.

48  2008 Pearson Education, Inc. All rights reserved. 48 Fig. 6.15 | Order in which a second-degree polynomial is evaluated.

49  2008 Pearson Education, Inc. All rights reserved. 49 6.7 Decision Making: Equality and Relational Operators Decisión basada en la verdad o falsedad de una condición – Equality operators – Relational operators

50  2008 Pearson Education, Inc. All rights reserved. 50 Fig. 6.16 | Equality and relational operators.

51  2008 Pearson Education, Inc. All rights reserved. 51 Common Programming Error 6.11 It is a syntax error if the operators ==, !=, >= and = and < =, respectively.

52  2008 Pearson Education, Inc. All rights reserved. 52 Common Programming Error 6.12 Reversing the operators !=, >= and and =<, respectively, is a syntax error.

53  2008 Pearson Education, Inc. All rights reserved. 53 Common Programming Error 6.13 Confusing the equality operator, ==, with the assignment operator, =, is a logic error. The equality operator should be read as “is equal to,” and the assignment operator should be read as “gets” or “gets the value of.” Some people prefer to read the equality operator as “double equals” or “equals equals.”

54  2008 Pearson Education, Inc. All rights reserved. 54 6.7 Decision Making: Equality and Relational Operators (Cont.) Si más de una variable es declarada bajo una sola declaración, los nombres deben separarse por comas (, )

55  2008 Pearson Education, Inc. All rights reserved. 55 6.7 Decision Making: Equality and Relational Operators (Cont.) objecto Date – Adquiere la fecha y hora local – Crea una nueva instancia de un objeto al utilizar el operador new seguido del tipo de objeto Date, y ( )

56  2008 Pearson Education, Inc. All rights reserved. 56 Fig. 6.17 | Using equality and relational operators (Part 1 of 3). Obtiene la fecha y hora del sistema. Obtiene solo la hora del sistema (0 - 23). Usa el enunciado IF para determinar si es de día, de tarde o de noche.

57  2008 Pearson Education, Inc. All rights reserved. 57 Fig. 6.17 | Using equality and relational operators (Part 2 of 3). Conditional statement: checks whether the current value of hour is greater than or equal to 12 If hour is 12 or greater (the previous condition was true), subtract 12 from the value and reassign it to hour Conditional statement: checks whether the current value of hour is less than 6 Conditional statement: checks whether the current value of hour is greater than or equal to 6 Envía el mensaje de acuerdo a la hora correspondiente.

58  2008 Pearson Education, Inc. All rights reserved. 58 Fig. 6.17 | Using equality and relational operators (Part 3 of 3).

59  2008 Pearson Education, Inc. All rights reserved. 59 Good Programming Practice 6.7 Include comments after the closing curly brace of control statements (such as if statements) to indicate where the statements end, as in line 36 of Fig. 6.17.

60  2008 Pearson Education, Inc. All rights reserved. 60 Good Programming Practice 6.8 Indent the statement in the body of an if statement to make the body of the statement stand out and to enhance program readability.

61  2008 Pearson Education, Inc. All rights reserved. 61 Good Programming Practice 6.9 Place only one statement per line in a program. This enhances program readability.

62  2008 Pearson Education, Inc. All rights reserved. 62 Common Programming Error 6.14 Forgetting the left and/or right parentheses for the condition in an if statement is a syntax error. The parentheses are required.

63  2008 Pearson Education, Inc. All rights reserved. 63 Common Programming Error 6.15 Placing a semicolon immediately after the right parenthesis of the condition in an if statement is normally a logic error. The semicolon would cause the body of the if statement to be empty, so the if statement itself would perform no action, regardless of whether its condition was true. Worse yet, the intended body statement of the if statement would now become a statement in sequence after the if statement and would always be executed.

64  2008 Pearson Education, Inc. All rights reserved. 64 Common Programming Error 6.16 Leaving out a condition in a series of if statements is normally a logic error. For instance, checking if hour is greater than 12 or less than 12, but not if hour is equal to 12, would mean that the script takes no action when hour is equal to 12. Always be sure to handle every possible condition.

65  2008 Pearson Education, Inc. All rights reserved. 65 Good Programming Practice 6.10 A lengthy statement may be spread over several lines. If a single statement must be split across lines, choose breaking points that make sense, such as after a comma in a comma-separated list or after an operator in a lengthy expression. If a statement is split across two or more lines, indent all subsequent lines.

66  2008 Pearson Education, Inc. All rights reserved. 66 Good Programming Practice 6.11 Refer to the operator precedence chart when writing expressions containing many operators. Confirm that the operations are performed in the order in which you expect them to be performed. If you are uncertain about the order of evaluation in a complex expression, use parentheses to force the order, exactly as you would do in algebraic expressions. Be sure to observe that some operators, such as assignment ( = ), associate from right to left rather than from left to right.

67  2008 Pearson Education, Inc. All rights reserved. 67 Fig. 6.18 | Precedence and associativity of the operators discussed so far.


Descargar ppt " 2008 Pearson Education, Inc. All rights reserved. 1 6 6 JavaScript: Introduction to Scripting."

Presentaciones similares


Anuncios Google