JavaScript
也称 ECMAScript as "JavaScript"
It is designed to run as a scripting language in a host environment, and it is up to the host environment to provide mechanisms机制 for communicating with the outside world.
The most common host environment is the browser, but JavaScript interpreters(翻译,解释程序) can also be found in a huge list of other places, including Adobe Acrobat, Adobe Photoshop, SVG images, Yahoo's Widget engine, server-side environments such as Node.js, NoSQL databases like the open source Apache CouchDB,
Overviews:
JavaScript is a dynamic language with types and operators, standard built-in objects, and methods.
Its syntax is based on the Java and C languages — many structures from those languages apply to JavaScript as well.
JavaScript supports object-oriented programming.
JavaScript also supports functional programming — functions are objects, giving functions the capacity to hold executable code and be passed around like any other object.
Js's types are :
Number
String
Boolean
-
Symbol
(new in ES2015) -
Object
null
undefine
- And there are some built-in
Error
types as well
Numbers:
parseInt()相当于to_i 。 parseInt('123',10);// 123,第二个参数是转换为几进制,默认10进制。类似的还有parseFloat()
特殊值: Infinity, -Infinity. 代表无穷数。 1/0; // Infinity
isFinite(1/0);// false, 是有限的吗?不是。
Strings
'hello'.length;// 5
String像对象,可当作对象使用一些方法。
'hello'.charAt(0); // "h"
'hello, world'.replace('hello','goodbye'); // "goodbye,world"
'hello'.toUpperCase(); // "HELLO"
othertypes
-
false
,0
, empty strings (""
),NaN
,null
, andundefined
all becomefalse.
- All other values become
true.
Boolean(''); - 例子Boolean('');// false
- Boolean(234); // true
Variables
New variables in JavaScript are declared using one of three keywords: let
, const
, or var
.
let allows you to declare block-level variables.只能在块内用。
for (let myLetVariable = 0; myLetVariable < 5; myLetVariable++) {
// myLetVariable is only visible in here }
const 就是常量 const Pi =3.14;之后就不能改变了,否则报错。Ruby是用全部大写字母表示常量。
var 是变量,var name = ''tom";
Operations:
和Ruby类似,+=,-= ,但多了 ++ ,—— 用法。
另外可以这么写 :如果有字符串,就合并为字符串。
'3'+4+5; // "345"
3+4+'5'; // "75"
<
, >
, <=
and >=
. 用于比较数字和字符串都可以。
== : 1 == true; //true
===同时比较type: 1 === true; // false
Control structures
if
var name = 'kittens';
if (name == 'puppies') {
name += ' woof';
} else if (name == 'kittens') {
name += ' meow';
} else {
name += '!';
}
name == 'kittens meow';
while和do..while
while (true) {
// an infinite loop!
}
var input;
do {
input = get_input();
} while (inputIsNotValid(input));
for循环3种。
for (var i = 0; i < 5; i++) {
// Will execute 5 times
}
JavaScript also contains two other prominent for loops: for
...of
for (let value of array) {
// do something with value
}
and for
...in
:
for (let property in object) {
// do something with object property
}
Objects
JavaScript objects can be thought of as simple collections of name-value pairs. As such, they are similar to: Hashes in Perl and Ruby.
"name" 是string类,value是任意类。两种写法:
var obj = new Object(); //类似Ruby obj = Class.new()
And:
var obj = {};
var obj = {
name: 'Carrot',
details: {
color: 'orange',
size: 12
}
};
Attribute access can be chained together:
很像obj.method,并且可以用chain式写法;也类似hash类的写法。
obj.details.color; // orange
obj['details']['size']; // 12
Function 特殊的object
类似Ruby中的类,其实js和Ruby都是everything is object.
function Person(name, age) {
this.name = name;
this.age = age;
}
// Define an object
var you = new Person('You', 24);
// We are creating a new person named "You" aged 24.
obj.name = 'Simon'; 等同于 obj["name"] = "Simon";用这种写法✅好
var name = obj.name;
(后面还有Function的知识)
Array也是特殊的对象
var a = new Array(); //类似Ruby, a = Array.new
a[0] = 'dog';
a[1] = 'cat';
a[2] = 'hen';
a.length; // 3 length是个方法
简单写法:
var a = ['dog', 'cat', 'hen']; // Ruby , a = ['dog', 'cat', 'hen']
a.length; // 3
Functions
Along with objects, functions are the core component in understanding JavaScript. The most basic function couldn't be much simpler:
function add(x, y) {
var total = x + y;
return total;
}
A JavaScript function can take 0 or more named parameters.
The function body can contain as many statements as you like and can declare its own variables which are local to that function.
The return
statement can be used to return a value at any time. If no return statement is used (or an empty return with no value), JavaScript returns undefined
.
add(); // NaN // You can't perform addition on undefined
You can also pass in more arguments than the function is expecting:多余的参数被忽视掉
add(2, 3, 4); // 5 // added the first two; 4 was ignored
例子1:
function avg() {
var sum = 0;
for (var i = 0, j = arguments.length; i < j; i++) {
sum += arguments[i];
}
return{ sum / arguments.length };
}
add(2, 3, 4, 5); // 3.5
例子1的简化写法,例子2,使用rest parameter operator和for...of循环:
function avg(...args) {
var sum = 0;
for(let value of args) {
sum += value;
}
return sum / args.length;
}
avg(2,3,4,5); //3.5
例子2的 重写法
function avgArray(arr) {
var sum = 0;
for(var i = 0, j = arr.length; i < j; i++) {
sum += arr[i];
}
return sum / arr.length;
}
avgArray([2,3,4,5]); // 3.5
javascript已经内置了avg(...numbers)方法
Custom objects
javasscript用函数作为class ,也作为方法。函数本身就是对象。
//类似一个类,可以定义对象
function makePerson(first, last) {
return {
first: first, last: last
};
}
//也类似一个方法 ,传递一个参数,返回结果。
function personFullName(person) {
return person.first + ' ' + person.last;
}
function personFullNameReversed(person) {
return person.last + ', ' + person.first;
}
//函数本身就是object
s = makePerson('Simon', 'Willison');
personFullName(s); // "Simon Willison"
personFullNameReversed(s); // "Willison, Simon"
可以用更好的写法:
function makePerson(first, last) {
return {
first: first,
last: last,
fullName: function() {
return this.first + ' ' + this.last;
},
fullNameReversed: function() {
return this.last + ', ' + this.first;
}
};
}
s = makePerson('Simon', 'Willison');
s.fullName(); // "Simon Willison"
s.fullNameReversed(); // "Willison, Simon"
the this
keyword. Used inside a function, this
refers to the current object.
this后面用.或[],便表示当前对象,如果没有使用则是全局对象。
用new的写法和this关键字来改进上面的写法:去掉了return{};
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = function() {
return this.first + ' ' + this.last;
};
this.fullNameReversed = function() {
return this.last + ', ' + this.first;
};
}
var s = new Person('Simon', 'Willison');
new关键字代替了return。
Functions that are designed to be called by new
are called constructor functions.
但是,嵌套的函数写法,尤其是有好几个函数,看起来很丑:改进:
function personFullName() {
return this.first + ' ' + this.last;
}
function personFullNameReversed() {
return this.last + ', ' + this.first;
}
function Person(first, last) {
this.first = first;
this.last = last;
this.fullName = personFullName;
this.fullNameReversed = personFullNameReversed;
}
看起来好多了,但是使用prototype方法,可以随时根据需要定义新的函数,更加方便:
function Person(first, last) {
this.first = first;
this.last = last;
}
Person.prototype.fullName = function() {
return this.first + "" + this.last;
}
Person.prototype.fullNameReversed = function() {
return this.last + ", " + this.first;
}
类似于类的继承,js里面,如果声明了一个string变量,使用String.prototype定义的方法,也可以用在这个变量上。因为string对象继承了String的方法。
同样,用prototype可以重新定义js的内置方法。
《Ruby元编程2》--239覆写方法:prepend,refinement细化,环绕别名。
镶嵌函数作用域,外部定义的变量,内函数可以用,但内函数定义的变量,外面不能用。
Closures
function makeAdder(a) {
return function(b) {
return a + b;
};
}
var x = makeAdder(5);
var y = makeAdder(20);
x(6); // ? 11
y(7); // ? 27
解释:
Whenever JavaScript executes a function, a 'scope' object is created to hold the local variables created within that function. It is initialized with any variables passed in as function parameters.
只要传进参数,函数初始化一个作用域对象,这个对象用来储存所有在函数中创建的本地变量。
所以当makeAdder() 被调用时,一个scope obj就被创建了,里面有一个property: a 。然后makAdder() 返回一个新创建的函数,这样x里面就储存了a。
A Closure is the combination of a function and the scope object in which it was created. 闭包可以储存state,因此闭包常常被用来取代对象。
闭包的原理详述(英文)https://*.com/questions/111102/how-do-javascript-closures-work
W3C.
Global Event Attributes
HTML 4 added the ability to let events trigger actions in a browser, like starting a JavaScript when a user clicks on an element.可以把这些属性加到html的元素中。
分几大类:
- window Event Attributes: <body>
- Form Event: almost in all html element,但主要是用在form elements.
- Keyboard Events: onkeydown
- Mouse Events: onclick ,ondblclick, 9个属性
- Drag Event(8个属性)
- Clipboard Events : oncoyp, oncut, onpaste
- Media Events:<audio> ,<img>,<video>等,但所有元素都能用。
JavaScript Can Change HTML Styless(css),Attributes, Content, Hide/Show
例子:
JavaScript Functions and Events
A JavaScript function is a block of JavaScript code, that can be executed when "called" for.
For example, a function can be called when an event occurs, like when the user clicks a button.
JavaScript in <head> or <body>
Scripts can be placed in the <body>, or in the <head> section of an HTML page。也可以放在 外部文件.js ; 用<script src="myScript1.js"></script>调用。可以是部分url.
JavaScript Output
- Writing into an HTML element, using innerHTML.
- Writing into the HTML output using document.write(). should only be used for testing.
- Writing into an alert box, using window.alert(). 弹出对话框
- Writing into the browser console, using console.log() ,一般用于debugging. 比如在chrome-inspect的控制台看js的输出。
var x, y; // How to declare variables
x = 5; y = 6; // How to assign values
z = x + y; // How to compute values
Js使用lower camel Case,首字母小写的驼峰写法。
Start the statement with var and separate the variables by comma:
var person = "John Doe", carName = "Volvo", price = 200;
var carName; //这个被声明但没有赋值,所以自动给一个值 undefined。
JS再声明没有任何效果。
var x = "5" + 2 + 3; //“523”
JavaScript Type Operators
Operator | Description |
---|---|
typeof | Returns the type of a variable |
instanceof | Returns true if an object is an instance of an object type |
typeof {name:'John', age:34} // Returns "object"
typeof [1,2,3,4]
// Returns "object" (not "array", see note below)
typeof null // Returns "object"
typeof function myFunc(){} // Returns "function"
如果调用函数但没有(),则返回函数定义本身。
如果调用函数,参数为空,则返回NaN. (not a number)
判断NaN 函数 isNaN(), NaN是一个数字, typeof Nan; // returns "number"
JavaScript Function Scope
In JavaScript there are two types of scope:
- Local scope
- Global scope
JavaScript has function scope: Each function creates a new scope.
Scope determines the accessibility (visibility) of these variables.
Variables defined inside a function are not accessible (visible) from outside the function.
如果你分配一个值给一个未声明的变量,这个变量自动成为全局变量,最好别这么用。
(Ruby 不需要声明。 全局变量$name)
Function Arguments
Function arguments (parameters) work as local variables inside functions.
函数的参数被看作本地变量。
HTML Events
HTML元素身上发生的事情。
An HTML event can be something the browser does, or something a user does.
- An HTML web page has finished loading
- An HTML input field was changed
- An HTML button was clicked
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>
<button onclick="this.innerHTML = Date()">The time is?</button> //this关键字,改变自己。
JS code 很长,一般event attribute用来调用function.
<button onclick="this.innerHTML = Date()">The time is?</button>
What can JavaScript Do?
Event handlers can be used to handle, and verify, user input, user actions, and browser actions:
- Things that should be done every time a page loads
- Things that should be done when the page is closed
- Action that should be performed when a user clicks a button
- Content that should be verified when a user inputs data
- And more ...
Many different methods can be used to let JavaScript work with events:
- HTML event attributes can execute JavaScript code directly
- HTML event attributes can call JavaScript functions
- You can assign your own event handler functions to HTML elements
- You can prevent events from being sent or being handled
- And more ...
The Difference Between Arrays and Objects
In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.
判断一个变量是不是Array类型。用 instanceof方法 :
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits instanceof Array // returns true
toString():把an array 变为a string of array values(comma separated)
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
//Banana,Orange,Apple,Mango
join(), pop(), push(), shift(),unshift()
concat() method creates a new array by merging (concatenating) existing arrays:
slice(1):去掉第几个元素。
sort():按照字母顺序排序
reverse(), 反向排列元素
break 和 continue
The continue statement (with or without a label reference) can only be used to skip one loop iteration.
The break statement, without a label reference, can only be used to jump out of a loop or a switch.
With a label reference, the break statement can be used to jump out of any code block:
var cars = ["BMW", "Volvo", "Saab", "Ford"];
list: {
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
break list; //直接跳出这个块了。
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
}
The constructor Property
The constructor property returns the constructor function for all JavaScript variables
false.constructor
// Returns function Boolean() {[native code]}
[1,2,3,4].constructor
// Returns function Array() {[native code]}
{name:'John',age:34}.constructor
// Returns function Object() {[native code]}
new Date().constructor
// Returns function Date() {[native code]}
function () {}.constructor
// Returns function Function(){[native code]}
Js也有RegExp,和Ruby里用法一样,多了个test()方法
JavaScript Errors - Throw and Try to Catch
The try statement lets you test a block of code for errors (点击链接,案例)
The catch statement lets you handle the errors.
The throw statement lets you create custom errors.
The finally statement lets you execute code, after try and catch , regardless of the result.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
JavaScript Throws Errors(点击链接,看案例)
When an error occurs, JavaScript will normally stop and generate an error message.
JavaScript will throw an exception (throw an error).
JavaScript will actually create an Error object with two properties: name and message.
The finally Statement
The finally statement lets you execute code, after try and catch, regardless of the result:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}
JavaScript Debuggers
Debugging is not easy. But fortunately, all modern browsers have a built-in JavaScript debugger.
use console.log() to display JavaScript values in the debugger window
debugger keyword stops the execution of JavaScript, and calls (if available) the debugging function.
在chrome的检查器中自动会弹到debugger关键字。
Hoisting: lift sth up
JavaScript Declarations are Hoisted
在用js编译代码的时候,先使用变量,然后再声明变量是可以的,因为js会默认把所有声明放到当前script/function的顶部,执行的时候还是先声明后使用。
不过(initialize)在声明的同时赋值,如 :var x = 5; 则不会被hoist。
把Declare Variables 放到顶部是好的做法。
Style Guide 代码规范
Always use 4 spaces for indentation of code blocks:
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
Avoid global variables, avoid new, avoid ==, avoid eval()
The === operator forces comparison of values and type:用来代替==
在js, 0代表false,
var x = 0;
if (x = 0) //false
floats不会非常精确。
最好:arrays use numbered indexs; object use named indexs(