# JavaScript Introduction

  • JavaScript is the behavioral layer of our web pages. HTML is structural, CSS is presentational
    JavaScript 是我们网页的行为层。HTML 是结构性的,CSS 是表现性的

  • Can access all the elements, attributes and text on a web page using the DOM (Document Object Model)
    可以使用 DOM(文档对象模型)访问网页上的所有元素、属性和文本

  • Can test for browsers features and capabilities, progressive enhancement
    可以测试浏览器的特性和能力,渐进增强

  • Modify elements and CSS properties to show, hide, and change element appearance
    修改元素和 CSS 属性以显示、隐藏和更改元素外观

  • Makes AJAX interactions possible
    使 AJAX 交互成为可能

  • Historically support between different browsers has sometimes been mixed.
    从历史上看,不同浏览器之间的支持有时是混合的。

    • Some browser implementations support some features and some use different names or syntax for a given feature.
      某些浏览器实现支持某些功能,而某些浏览器实现对给定功能使用不同的名称或语法。
  • Not Related to Java Programming Language
    与 Java 编程语言无关

  • Originally named LiveScript and created by Brendan Eich at Netscape in 1995. Later renamed JavaScript for marketing reasons because of popularity of Java Language at the time.
    最初命名为 LiveScript,由网景公司的 Brendan Eich 于 1995 年创建。后来由于当时 Java 语言的流行,出于市场原因更名为 JavaScript。

  • Standardized by ECMA technically ECMAScript
    ECMA 技术上标准化的 ECMAScript

    • Almost universally supported legacy version is ECMAScript 5 – JS 1.8.5
      几乎普遍支持的旧版本是 ECMAScript 5 – JS 1.8.5
    • ES6+ is the newer versions, use it now in most modern browsers or with a complier like https://babeljs.io
      ES6+ 是较新的版本,现在可以在大多数现代浏览器或像这样的编译器中使用它
    • Newest version is 11 edition or 2020
      最新版本是 11 版或 2020
  • Lightweight Object-oriented scripting language
    轻量级面向对象的脚本语言

    • Procedural, object-oriented (prototype-based), and functional style
      过程式、面向对象(基于原型)和函数式风格
  • Dynamic Language
    动态语言

    • Doesn't need to be compiled to machine code
      不需要编译成机器码
    • Loosely typed - Don't need to declare variable types
      松散类型 - 不需要声明变量类型
  • Read and interpreted on the fly
    即时阅读和解释

# References

Mozilla JavaScript Guide

Wikipedia JavaScript Entry

Wikipedia JavaScript Entry

JavaScript and Basic Programming Introduction Reading

ECMAScript 11th edition – 2020 Specification

ECMAScript 6th edition – 2015 Specification

ECMAScript 5.1 edition – 2011 Specification

# Use script tag

Embedded Scripts 嵌入式脚本

Use script tags

<script> JS Here </script>
External Scripts 外部脚本

Use script tag with src attribute

<script src="myscript.js"></script>

使用带有 src 属性的脚本标签

  • Script tag must be empty inside
    脚本标签内部必须为空
  • Can be placed anywhere on the page, blocks when executing
    可以放置在页面任意位置,执行时阻塞
  • Most commonly in head section or at the bottom of the body before the closing body tag
    最常见于头部或 body 底部,在 body 标签结束之前
  • Type attribute was required in <= html4 but not html5
    <= html4 中需要类型属性,但 html5 中不需要
<script type="text/javascript"></script>
  • There is an async attribute in html5, async="async" & defer="defer”
    html5 中有一个 async 属性
    • Async executes as page parsing.
      Async 异步作为页面解析执行。
    • Defer executes script when page finishes parsing.
      Defer 在页面完成解析时执行脚本。
    • When either is not present (default), executes immediately then finishes parsing page
      当一个都不存在时(默认),立即执行然后完成解析页面

# Other features

  • JavaScript is case-sensitive foo not equal Foo
    JavaScript 区分大小写, foo 不等于 Foo
  • Made up of statements which should end with a semicolon.
    组成语句应以分号结尾
  • Contains reserved words you can not use. Search for a list of JavaScript reserved words for details.
    包含不能使用的保留字。搜索 JavaScript 保留字列表以获取详细信息。
  • Comments can be single or multi line
    注释可以是单行或多行
  • Single Line – two slashes
    单行 – 两条斜线
    // This is a comment
  • Multi Line – similar to css
    多行类似于 css
    /* This is a comment */

# JavaScript Language Features and Syntax

# Variables 变量

  • Variables hold values or objects
    变量保存值或对象
  • Declared with var keyword (pre ES6)
    使用 var 关键字声明(ES6 之前)
  • Set value with single = sign
    用单个 = 符号设置值
  • Names are case sensitive
    名称区分大小写
  • Names must begin with a letter or the underscore
    名称必须以字母或下划线开头
  • Can be a set of very basic data types: numbers, strings, booleans, objects, functions, and undefined values
    可以是一组非常基本的数据类型:数字、字符串、布尔值、对象、函数和未定义的值
  • No special characters in name (! . , / \ + * =)
    名称中没有特殊字符
  • Has functional scope – not block scope (ES5 with var)
    有函数作用域 —— 不是块作用域(ES5 with var)
  • If a variable is declared in a function without var keyword it's global
    如果在没有 var 关键字的函数中声明变量,则它是全局变量
var foo;
var foo = 5;
  • ES6 Introduces two new variable declarations let and const .
    ES6 引入了两个新的变量声明 letconst
    var vs let vs const article

  • ES6 Introduces Block Scope
    引入块作用域

# Array - grouping/list of objects 对象的分组 / 列表

  • Arrays are defined with - new Array() or [ ]
    数组定义为 - new Array() or [ ]

  • Zero indexed so first element is - arrayname[0]
    零索引所以第一个元素是 - arrayname[0]

# Statements 语句

  • Statements are commands to the browser that are
    executed in order
    语句是浏览器按顺序执行的命令

  • Should end with a semicolon but not required. JS has ASI
    应该以分号结尾,但不是必需的。JS 有 ASI

  • May span multiple lines if written carefully
    如果仔细书写,可能会跨越多行

  • Multiple statements may be on the same line if separated by a semicolon.
    如果用分号分隔,多个语句可以在同一行。

# Blocks

  • Statements can be grouped together in blocks with the curly brackets { }
    语句可以用大括号 { } 组合在块中

  • Usually, blocks are used when defining functions or using conditionals or loops
    通常,在定义函数或使用条件或循环时使用块

  • JavaScript does not use block scope like most programming languages.
    JavaScript 不像大多数编程语言那样使用块作用域。
    It has function scope.
    它具有功能范围。
    This can change in ES6, but you need to understand what version and syntax you’re using and how it will behave.
    这在 ES6 中可能会发生变化,但您需要了解您使用的版本和语法以及它的行为方式。

# Basic Mathematical Operators

  • Addition + (plus operator is also used to concatenate strings) 加号运算符也用于连接字符串
  • Subtraction -
  • Multiplication *
  • Division /
  • Modulus (division remainder) % 模量(除法余数)
  • Increment ++
  • Decrement --
  • Add to self and reassign +=
var car = 5; car += 2; // car is now 7

# Functions 函数

  • Named blocks of code that can be called and executed by events or other code, may take parameters
    可以被事件或其他代码调用和执行的命名代码块,可以带参数

  • Functions are objects in JavaScript
    函数在 JavaScript 中是对象

    function funcname (var1, var2,) {
        // code block (may make use of parameters)
    }
  • The return statement will stop executing the function and return the value
    return 语句将停止执行函数并返回值

    function addnum(n1, n2) {
        return n1 + n2;
    }
  • Can be created with Function Declarations or Function Expressions
    可以使用函数声明或函数表达式创建

Function Declarations 函数声明
Can be defined after being used. Defined in initial parse phase.
使用后可以定义。在初始解析阶段定义。
function myFunction() {
    // statements;
}
Function Expression 函数表达式
Must be defined before being used. Little clearer that the var myFunction holds a function. Defined during execution.
使用前必须定义。 var myFunction 包含一个函数。在执行期间定义。
var myFunction = function(){
statements;
};

# Functions 内置函数

  • JavaScript has many built in functions as part of the language and specification.
    JavaScript 有许多内置函数作为语言和规范的一部分。

  • The functions available will vary depending on the execution environment.
    可用的功能会因执行环境而异。

  • Useful basic built-in functions:
    有用的基本内置函数

    • alert()
    • confirm()
    • prompt()
    • console.log()
    • Number() vs parseInt() or parseFloat()
    • Math and Date objects
    • Many more

# Comparison Operators 比较运算符

Comparisons are used to compare the value of two objects and return true or false
比较用于比较两个对象的值并返回真或假

  • == Is equal to
  • != Is not equal to
  • === Is identical to (equal to and same data type)
    等同于(等于和相同的数据类型)
  • !== Is not identical to
  • > Is greater than
  • >= Is greater than or equal to
  • < Is less than
  • <= Is less than or equal to
alert( 5 > 1 ); // Will alert “true”

# Conditional Statements 条件语句

  • if statements
  • else statements
  • else if statements
if ( condition ) {
    // run this block
} else if (condition) {
    // run this block
} else {
}

# Basic Loops

for
loops through a block a specific # of times
循环一个块特定的次数
while
loops through a block while condition true
在条件为真时循环块
do...while
loops through block once then repeats as long as a condition is true
循环一次块,然后只要条件为真就重复
for...in
loops through all properties of an object, be careful with this one can be error prone. Do not use to loop through an array.
遍历对象的所有属性,小心这个很容易出错。不要用于遍历数组。
For Loop Syntax
for (initialize the variable; test the condition; alter the value;){
    // code to loop here
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code

# primitave Values 原始值

undefinedused for unintentionally missing value用于无意中丢失的值
nullused typically for intentionally missing values通常用于有意缺失值
booleanstrue/false, used for logical operationstrue/false,用于逻辑运算
numbers(25, 3.1415) all numbers but limited precision as you get further from 0 and used for math所有数字,从 0 开始使用和使用,精度有限
bigints(uncommon, new) large integers for more precision and math on big numbers 232131231233123123n大整数,可在大数上获得更高的精度和数学运算
stringstext and immutable, all possible strings exist as values文本和不可变的,所有可能的字符串都作为值存在
symbols(uncommon)
functionsused to refer to code and execute that code用于引用代码并执行该代码
objectsgroup related data and code对相关数据和代码进行组合

typeof() operator will tell you the type of value a variable points to
typeof() 返回变量指向的值的类型

# Objects 对象

  • Objects - All items except core data types in JavaScript are objects including functions
    对象 - JavaScript 中除核心数据类型外的所有项目都是包括函数在内的对象

  • Objects are basically a custom data structure
    对象基本上是一个自定义的数据结构

  • No class system in JavaScript like in other programming languages. Uses Prototypes instead. Has a system of Prototype Inheritance. Class keyword added in ES6.
    JavaScript 中没有像其他编程语言那样的类系统。改为使用 原型 。拥有原型继承系统。ES6 中添加了 Class 关键字。

  • The browser is the window object, the html page is the document object
    该浏览器是窗口对象,html 页面是文档对象

  • Objects are composed of properties and methods
    对象由属性和方法组成

    • Properties are basically variables
      属性基本上是变量
    • Methods are basically functions
      方法基本上是函数
  • Access an objects property – obj.propertyName or obj["propertyName"]
    访问对象属性

  • Execute an object method – obj.methodName()
    执行一个对象方法

# Create

  • Created by a function with new keyword
    由带有 new 关键字的函数创建

    var obj = new Object();
  • Created with an object literal
    用对象字面量创建

    var obj = {};
    var obj = { key: value, key2: value2 };
    • Key needs to be a string with no spaces, can not start with number or special character
      Key 必须是没有空格的字符串,不能以数字或特殊字符开头
      var obj = { color: "red", quantity: 5, instock: true };

# Access or set properties

  • Access or set properties with dot notation
    使用点符号访问或设置属性
    obj.color = "blue"; // sets color of obj to blue
    obj.quantity; // would be equal to 5
  • Can also set or execute methods this way
    也可以通过这种方式设置或执行方法
  • You can also access properties with the array like syntax of obj["color"]
    还可以使用类似数组的语法访问属性
  • Useful when you need the property value to come from another variable
    当需要的属性值来自另一个变量时很有用

# JavaScript Object Literal format

对象文字格式

  • An object literal is a comma separated list of name value pairs wrapped in curly braces.
    对象字面量是用大括号括起来的逗号分隔的名称值对列表。
var myObject = {
        stringProp: 'some string',
        numProp: 2,
        booleanProp: false
    };
  • Value can be any JavaScript Datatype including a function or other object.
    值可以是任何 JavaScript 数据类型,包括函数或其他对象。

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics

# JavaScript & DOM additional information

MDN Links to Web Technology Tutorials

  • https://developer.mozilla.org/en-US/docs/Web/Tutorials
  • https://developer.mozilla.org/en/docs/JavaScript
  • https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction
  • https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model
  • https://developer.mozilla.org/en-US/docs/Web/API/element

# Quiz 1-3

  1. The HTTPS protocol uses port 80 by default.

  2. In what year did Tim Berners-Lee write the original web proposal?

    • 1991
    • 1989
    • 1990
    • 1995
  3. Which HTTP method is used when you click a link?

    • HEAD
    • POST
    • GET
    • OPTIONS
  4. Any HTML content that you want to appear at the top of the page in the browser should be placed in the section of the HTML document.

    您希望出现在浏览器页面顶部的任何 HTML 内容都应放置在 HTML 文档的部分中。

  5. Tim Berners-Lee also created the CSS specification.

  6. Which HTTP status code means everything went well and the response is done?

    • 200
    • 301
    • 404
    • 500
  7. Which HTML attribute value must be unique in the document?

    • class
    • id
    • title
    • src
  8. An HTML div element is a block level tag.

  9. Which HTTP status code means the resource has moved permanently?

    • 200
    • 301
    • 403
    • 501
  10. In an HTTP 1.1 request the host header is required.

  11. Which CSS selector adds the highest level of specificity?

    • class
    • element
    • id
    • pseudo-elements
    • pseudo-classes
  12. When using an HTML label element with the explicit association, which from control attribute should the label’s for attribure reference?

    • name
    • id
    • title
    • value
  13. A user can modify a hidden form control.

  14. Which is the preferred way to add CSS to an HTML document?

    • external
    • embedded
    • inline
  15. When using a link element to connect an external style sheet you use the src attribute on the link elmement to point to the file location.

  16. Which attribute is used on an HTML form control to identify the value of the control when the form is submitted to the processing script?

    • name
    • id
    • value
    • for
  17. Which JavaScript script tag attribute causes the browser to executing that script while parsing the rest of the page?

    • defer
    • async
    • type
  18. Semicolons are not required in JavaScript.

  19. In JavaScript, the == comparison operator compares value and data type.

  20. In JavaScript which way of defining functions allows you to call the function before it is defined in the script?

    • Function Declaration
    • Function Expression
  21. In JavaScript comments can only be single line and must start with // .

  22. In an HTML5 document you must have the type=“text/javascript” attribute/value pair on a script tag.

  23. In JavaScript variables declared with the var keyword have block scope.