Javascript快速入门
Javascript的来源
- JavaScript was developed by a gentleman named Brendan Eich, who was working for Netscape
- Mocha, then LiveScript, and finally JavaScript.
- The first browser to support JavaScript was Netscape Navigator 2.0, way back in late 1995
Javascript在页面中的使用方式
- embed your JavaScript code right inside script tags.
<script>
alert("I'm learning JavaScript");
</script>
- The second way to get JavaScript onto your page is to link to a .js file:
<script src="somefile.js"></script>
变量类型
var name = "Joe",
age = 45,
job = "plumber"; alert( name ); // Joe
String
alert( "John says \"What are you doing?\"" );
alert( '"Let\'s go out for lunch."' );
Numbers
alert( 3.45e5 ); // 345000
alert( 123e-3 ); // 0.123
Booleans
true and false
Null and Undefined
Object
var obj = {
name : "Andrew",
age : 20,
awake : true,
company : {
name : "XYZ Ltd.",
id : 12345
}
};
var obj = {
name : "Joe", age : 10 };
alert( obj.name ); // "Joe“
alert( obj["age"] ) ; // 10
Array
var arr = ["string", 20, false];
alert( arr[0] ); // "string"
Date
new Date("January 17, 2012")
new Date(2009, 3, 20, 17, 30)
Semicolons
var someVar = "value";
someFunction("parameter");
if (true) {
doThis();
}
注释
// This is a useless comment
/* file: navigtion.js
author: Andrew Burgess date: July 2, 2011
purpose: provides animation for the site navigation
*/
运算符
Arithmetic Operators
var four = 2 + 2, //addition operator hour = 24 - 13, // subtraction operator
seventy = 7 * 10, // multiplication operator avg_days_per_week = 365 / 52, // division operator remainder = 31 % 2, // modulus operator
msg = "the time is " + hour + " o'clock"; // addition operator used
on strings
console.log(four); // 4
console.log(hour); // 11
console.log(seventy); // 70
console.log(avg_days_per_week); // 7.019230769230769
console.log(remainder); // 1 console.log(msg); // "the time is 11 o'clock"
Comparison Operators
alert( 10 < 5 ); // false
alert( 10 > 5 ); // true
alert( 4 <= 3 ); // false
alert( 4 === 3 ); // false
alert( "cat" > "dog" ); // false
alert( "bacon" > "chunks" ); // false
alert( "cats" >= "cats" ); // true
alert( "fishing" <= "sleeping" ); // true
alert( "cat" > "CAT" ); // true
Unary Operators
var i = 0;
i++;
alert(i); // 1
++i;
alert(i); // 2
i--;
alert(i); // 1
--i;
alert(i); // 0
Assignment Operators
var num = 10;
num += 5; // same as num = num + 5
alert(num); // 15
num -= 3; // same as num = num - 3
alert(num); // 12
num *= 2; // same as num = num * 2
alert(num); // 24
num /= 6; // same as num = num / 6
alert(num); // 4
num %= 3; // same as num = num % 3
alert(num); // 1
Boolean Operators
var a = true;
var b = false;
alert( a && b ); // false
alert( a || b ); // true
var day = 14, year = 2011;
alert( day > 10 || year === 2011 ); // true
alert( day < 20 && year >= 2010 ); // true
条件语句
If Statements
var year = 2011, msg = "In the ";
if (year > 2000) {
msg += "twenty-first century";
} else {
msg += "twentieth century";
}
console.log(msg); // In the twenty-first century
Switch Statements
var order_size = "medium";
switch (order_size) {
case "small":
alert("small");
break;
case "medium":
alert("medium");
break;
case "large":
alert("large");
break;
case "extra large":
alert("extra large");
break;
default:
alert("something else?");
}
Conditional Operator
var temp = 18,
msg = (temp > 10) ? "Today was warm" : "Today was cold";
alert(msg);
循环语句
For Loops
var names = ["Ringo", "John", "Paul", "George"];
for (var i = 0; i < names.length; i++) {
alert("Say hello to " + names[i]);
}
var i = 0;
for ( ; names[i] ; ) {
//do something
i++;
}
While Loop
var not_home = true, miles_driven = 0;
while (not_home) {
miles_driven += 1; // drive another mile
if (miles_driven === 10) {
not_home = false;
}
}
alert(miles_driven);
For Loop, Revisited
var person = {
name : "Jules Verne",
job : "Author",
year_of_birth: 1828,
year_of_death: 1905
},
prop;
for (prop in person) {
alert("His " + prop + " is " + person[prop]);
}
函数
Function is a object
function getGreeting(hour)
{
var hour = 10,
message;
if (hour < 12) {
message = "Good Morning!";
} else if (hour < 17) {
message = "Good Afternoon!";
} else {
message = "Good Evening!";
}
return message;
}
var message = getGreeting( 16 ); // 4 PM
alert(message); // Good Afternoon!
Functions
function getGreeting(hour)
{
var hour = 10,
message;
var msg1 = getGreeting(10),
msg2 = getGreeting(1,2,3,4,5,6, "and on"),
msg3 = getGreeting(),
msg4 = getGreeting("five o'clock");
}
return message;
}
var message = getGreeting( 16 ); // 4 PM
alert(message); // Good Afternoon!
function sum()
{
var sum = 0, i;
for ( i = 0 ; arguments[i]; i++)
{
sum += arguments[i];
}
return sum;
}
var sum1 = sum(1, 2),
sum2 = sum(100, 75, 40),
sum3 = sum(9, 1.4, 8, 2, 79, 3234, 6, 4, 5e3, 5);
alert(sum1); // 2
alert(sum2); // 215
alert(sum3); // 8348.4
Anonymous Functions
function () {
return "this function has no name";
}
var hi = (function () {
return function () {
return "Hi";
}
};
String Methods
- length
- indexOf
- slice, substr, and substring
- split
- toLowerCase and toUpperCase
Numbers Methods
- toExponential
- toFixed
- toPrecision
- parseInt
- parseFloat
Date Methods
- getDate, getDay, getFullYear, getHours, getMinutes, getMonth , getSeconds, getTime, getTimezoneOffset
- setDate, setMinute, setFullYear, …
- parse
Array Methods
- join
- pop / shift
- push / unshift
- reverse
- slice
- sort
["d", "e", "c", "a", "b"].sort();
[0, 5, 10, 15, 20, 25] .sort();
- var
arr = [5, 2, 3, 4, 1];
arr.sort(function (a, b) {
return a - b;
});
console.log(arr); // [1, 2, 3, 4, 5];
Math Methods
- min
- max
- random
- round / ceil / floor
- pow
this
this will reference the global object
var my_variable = "value";
function my_function ()
{
return "another_value" }
alert( this.my_variable ); // "value”
alert( this.my_function() ); // "another_value"
new
The new Keyword
function Truck(model) {
this.num_of_tires = 4;
this.kilometers = 0;
this.model = model;
}
var my_truck = new Truck("Hercules");
console.log(my_truck);
call and apply
two methods that functions have by default
```javascript
function Truck (model, num_of_tires) {
this.num_of_tires = num_of_tires;
this.kilometers = 0;
this.model = model;
}
var basic_vehicle = {
year : 2011 };
Truck.call(basic_vehicle, "Speedio", 4);
console.log(basic_vehicle);
对象内部的属性访问
var waitress = {
name : "Ashley",
greet: function (customer)
{
customer = customer || “there";
return "Hi " + customer + “! My name is " + this.name + "; what can I get you?";
}
};
alert( waitress.greet("Joe") );
// Hi Joe! My name is Ashley; what can I get you?
Object Oriented JavaScript
function Computer (name, ram_amount, memory_amount) {
this.name = name;
this.RAM = ram_amount; // in GBs
this.space = memory_amount; // in MBs
}
my_computer = new Computer("MacBook", 2, 250000 );
console.log(my_computer);
function Computer (name, ram_amount, memory_amount) {
this.name = name;
this.RAM = ram_amount;
this.space = memory_amount;
this.files = [];
this.store_file = function (filename, filesize) {
this.files.push(filename);
this.space -= filesize;
};
}
Computer.prototype.store_file = function (filename, filesize) {
this.files.push(filename);
this.space -= filesize;
};
function Product(name) {
if (name) {
this.name = name;
}
}
Product.prototype.name = "To be announced";
Product.prototype.rating = 3;
var ipad = new Product("iPad");
alert( ipad.name ); // "iPad";
alert( ipad.rating ); // 3
function Person(name) {
this.name = name;
}
Person.prototype.legs = 2;
var person = new Person("Joe"), prop; for (prop in person) {
console.log(prop + ": " + person[prop]);
}
// in console:
// name : Joe
// legs: 2
闭包
var revealSecret = (function () {
var secretNumber = 1024;
return function (password) {
if (password === "please") {
return secretNumber++;
}
return 0;
};
}());
console.log( revealSecret("please") ); // 1024
console.log( revealSecret("please") ); // 1025
DOM
<p>We're learning about the <em>Document Object Model </em>, or
<strong>DOM</strong>.</p>
<div class="product">
<h2> Product Name </h2>
<img src="pic.jpg" />
<p> Description </p>
</div>
document.getElementById("id_name")
document.getElementsByClassName document.getElementsByTagName
var products =
document.getElementsByClassName("product"),
i = 0,
child;
for ( ; i< products.length; i++)
{
child = products[i].firstChild;
while (child.nodeType !== 1) {
child = child.nextSibling;
}
console.log(child);
}
通过ID的属性获得对应的元素
// 原 始 的 w3c DOM document.getElementById(‘elementId’);
$(‘elementId’); //Prototype, MooTools
$(‘#elementId’); //jQuery
Y.one(‘#elementId’); //YUI3
dojo.byId(‘elementId’); //Dojo
Ext.getDom(‘elementId’); //Ext JS3
元素遍历
- 从具有指定id属性的元素开始,到达最近的class属性为category的
<h2>
元素然后遍历这个元素的兄弟元素直到遇到一个class属性为summary 的元素- $(‘someDeeplyNestedElement’).up(‘h2.category’).n ext(‘.summary’);
- //找到带有名为sifr的CSS class的元素,设置这些元素的直接容器的CSS文本缩进属性
- $$(‘a.sifr’).invoke(‘up’).invoke(‘getStyle’, ‘text- indent: -9999px’);