javascript training
DESCRIPTION
给快车做的Javascript培训TRANSCRIPT
Javascript 基础和进阶
数据类型篇
马士华
Javascript 简介• JavaScript 是一种轻型的解释型的程序语言。• JavaScript 最开始就是被设计成一种彻底的
面向对象语言。
如何调试脚本 调试 js 脚本推荐使用 Firebug console Fire
bug 提供了许多的有用的工具,如错误控制台, HTTP 请求日志,调试,以及元素查看。
Firebug console 调试例子: var x = true;
if ( x ) console.log("x defaulted to true")
else console.log("x defaulted to false")
String
例子: "I'm a String in JavaScript!"
typeof "some string"; //"string"
运算符:+
“hello,” + “javascript”
String
• 引号的用法:• "You make 'me' sad.“
• 'Holy "cranking" moses!'
• "<a href=\"home\">Home</a>"
String
• 方法:• "hello".charAt(0) // "h" • "hello".toUpperCase() // "HELLO" • "Hello".toLowerCase() // "hello" • "hello".replace(/e|o/g, "x") // "hxllx" • "1,2,3".split(",") // ["1", "2", "3"] • “hello". substring(1,4) //ell• “hello". substr(1,2) //el• “hello". Indexof(‘e’,0) //1• “hello".lastIndexof(‘l’,’hello’.length-1) //3
String
• 长度属性:• "Hello".length // 5
• "".length // 0
• 默认的 Boolean 属性:• !"" // true
• !"hello" // false
Number
Javascript 并不区分整形和浮点,所有的数字都用浮点来表示( IEEE754 标准的浮点格式,即 double )。
例子:123 , 123.68typeof 123 // "number" typeof 123.68// "number" 运算符:所有的 C 语言中对数字的运算符 (+, -, *, /, %, =, +=,
-=, *=, /=, ++, --)
Number
• 默认的 Boolean 属性:!0 // true !1 // false !-1 // false • parseInt & parseFloatparseInt("123") = 123 (implicit decimal)parseInt("010") = 8 (implicit octal) parseInt("010", 10) = 10 (explicit decimal)parseInt("11", 2) = 3 (explicit binary)parseFloat("10.10") = 10.1
Number
Numbers to Strings"" + 1 + 2; // "12" "" + (1 + 2); // "3" NaN & Infinity parseInt("hello", 10) // NaN isNaN(parseInt("hell
o", 10)) // true 1 / 0 // Infinity typeof NaN // "number" typeof Infinity // "number"
Boolean
Boolean 只有 true 和 false 的值if ( true ) console.log("always!") if ( false ) console.log("never print!") 运算符:& ||true & true //truetrue & false //falsetrue || false //truefalse || false //false
||
运用 || 运算符可以产生短路现象:var t,y,x=0,z=1,w={} ;var c = t || 0; //now c=0 var c = t || y || 0; //now c=0var c = t || y || x || 0; //now c=0 var c = t || y || x || z || 0; //now c=z=1 var c = z || y || x || t || 0; //now c=z=1var c = t || y || w || t || 0; //now c=w
Object
在 Javascript 中任何东西都是 Object. 下面是Object 的表达式。
var x = {};
var y = { name: "Pete", age: 15 };
typeof {} // "object"
Object
. 符号:用 . 符号读取和写入 Object 的属性。y.name // "Pete"
y.age // 15
x.name = y.name + " Pan" // "Pete Pan
x.age = y.age + 1 // 16
Object
[] 符号也可用 Array 的符号 [] 操作。var operations = { increase: "++", decrease: "--“ } var operation = "increase";operations[operation] // "++";operations["multiply"] = "*"; // "*" x [" age "] //16
Object
遍历:var obj = { name: "Pete", age: 15 }; for(key in obj) {console.log("key=" + key, "value="+obj[key]); } // "key=name", "value=Pete" // "key=age", "value=15" 默认的 Boolean 属性 :!{} //false
Array
例子:var x = []; var y = [1, 2, 3];typeof []; // "object" typeof [1, 2, 3]; // "object“读取和写入值:x[0] = 1; y[2] // 3
遍历:for (var i = 0; i < a.length; i++) { // Do something with a[i] } for (var i = 0, j = a.length; i < j; i++) { // Do something with a[i] } for (var i = 0, item; item = a[i]; i++) { // Do something with item }
Array
Array
Length 可以用来添加一个元素到 Array 的结尾,等同于 push 方法
var x = [];
x.push(1);
x[x.length] = 2;
x // 1, 2
Array
方法:var x = [0, 3, 1, 2]; x.reverse() // [2, 1, 3, 0] x.join(" – ") // "2 - 1 - 3 - 0" x.pop() // [2, 1, 3] x.unshift(-1) // [-1, 2, 1, 3] x.shift() // [2, 1, 3] x.sort() // [1, 2, 3] x.splice(1, 2) // return [2, 3] a=[1]• 默认的 Boolean 属性:![] // false
未定义的变量和未赋值的变量• var s;
• console.log(d) //wrong,d is not defined
• console.log(typeof d) //undefined
• console.log(s) //undefined
typeof 和 constructorif ( typeof num == "string" ) num = parseInt( num );if ( typeof arr == "string" ) arr = arr.split(",");
if ( num.constructor == String ) num = parseInt( num );if ( str.constructor == Array ) str = str.join(',');变量类型检查
——————————————————————————————— Variable typeof Variable Variable.constructor ——————————————————————————————— {an:"object"} “ object” Object ["an","array"] “ object” Array function(){} “ function” Function "a string" “ string” String 55 ” number” Number true “ boolean” Boolean new User() “ object” User ——————————————————————————————————
Function
例子:function named() {} var handler = function() {} (function(){if(console)
window.log=console.log})()var a = 1;setTimeout(function(){log(a);},1000);
Function
Arguments
function log(x) {
console.log(typeof x, arguments.length);
}
log(); // "undefined", 0
log(1); // "number", 1
log("1", "2", "3"); // "string", 3
Function
Call and Apply我们同样可以指定上下文到 function 通过 call 和 ap
ply 方法,唯一不同的是 call 的参数必须是 Array或 Arguments 对象。 Apply 接受 array 为 Arguments 。
function scope() { console.log(this, arguments.length); } scope() // window, 0 scope.call("foobar", [1,2]); // "foobar", 1scope.apply("foobar", [1,2]); // "foobar", 2
Function
Context在 javascript 中, this 总是指导当前的上下文。默认是 wind
ow 对象。var flashget=“flashget”console.log(window.flashget) // “flashget”下面的例子, this 指到 id 为 t 的元素中去了Object.prototype.getHTML =function(){
if(this['nodeName'])console.log(this.innerHTML);
}document.getElementById("t"). getHTML();
Function
改变函数上下文的示例 function changeColor( color ) {this.style.color = color;}//wrong,because window desn't hava style attributechangeColor( "white" );var main = document.getElementById("main");changeColor.call( main, "black" );function setBodyColor() { changeColor.apply( document.body, arguments );}setBodyColor( "black" );
Function
Scope (作用域) 作用域是 JavaScript 中一个较难处理的特性。所有面向
对象的编程语言都有某种形式的作用域;这要看是什么上下文约束着作用域。在 JavaScript 里,作用域由函数约束,而不由块约束 ( 如 while,if, 和 for 里的语句体 ) 。
var v = "globe";function scope() {
console.log(v) //undefinedvar v = "in a function“; console.log(v); //in a function
}scope() console.log(v) //globe
Function
虽然在全局变量中可以不使用 var ,但是在局部变量中一定要使用 var ,下面代码可以说明问题。
var v = "globe";function scope() {
console.log(v); // globev = "in a function" console.log(v); // in a functionm = "in a function define a globe“
}scope() console.log(v) //in a functionconsole.log(m) // in a function define a globe
FunctionClosures(闭包) 闭包意味着内层的函数可以引用存在于包绕它的函数的变量,即使外
层的函数的执行已经终止。 也意味着内层的函数可以创建外面不可访问的变量和方法。
var obj = document.getElementById("main");obj.style.border = "1px solid red";setTimeout(function(){ obj.style.display = 'none';}, 1000);function delayedAlert( msg, time ) { setTimeout(function(){ alert( msg ); }, time );}delayedAlert( "Welcome!", 2000 );
FunctionClosures(闭包)使用匿名函数激发一个创建多个闭包函数所需的作用域的例子 :var items = document.getElementsByTagName("a");for ( var i = 0,item; item = items[i]; i++ ){
(function(){ var href = item.getAttribute("href"); item["onclick"] = function(){
console.log( href ); return false;
}; })(); item.setAttribute("href","#");
}
FunctionClosures(闭包)function associateObjWithEvent(obj, methodName){
return ( function(e){ e = e||window.event; return obj[methodName](e, this);
});}function DhtmlObject(elementId){
var el = getElementWithId(elementId); if(el){
el.onclick = associateObjWithEvent(this, "doOnClick"); el.onmouseover = associateObjWithEvent(this, "doMouseOver"); el.onmouseout = associateObjWithEvent(this, "doMouseOut");
}}DhtmlObject.prototype.doOnClick = function(event, element){ // doOnClick method body.}DhtmlObject.prototype.doMouseOver = function(event, element){ // doMouseOver method body.}DhtmlObject.prototype.doMouseOut = function(event, element){ // doMouseOut method body.}
FunctionReference (引用)
JavaScript 的一个重要的方面是引用的概念。引用就是指向对象实际位置的指针。这是一项极其强大的功能。引用总是只指向最终被引用的对象,而不会是引用本身。 Number , Boolean, null和为定义的值为基本类型。对象,数组,函数为引用类型。
var obj = new Object();var objRef = obj;obj.oneProperty = true;console.log( obj.oneProperty === objRef.oneProperty ); //truevar items = new Array( "one", "two", "three" );var itemsRef = items;items.push( "four" );console.log( items.length == itemsRef.length ); //truevar items = new Array( "one", "two", "three" );var itemsRef = items;items = new Array( "new", "array" ); //let items refer to new object.Console.log( items !== itemsRef ); //true
Function函数重载
function sendMessage( msg, obj ) { if ( arguments.length == 2 ) obj.handleMsg( msg ); else console.log( msg );}
sendMessage( "Hello, World!" );sendMessage( "How are you?", { handleMsg: function( msg ) { console.log( "This is a custom message: " + msg ); }});
Function继承 JavaScript 使用了一种独特的对象创建和继承的方式,称为原型继承( prot
otypal inheritance )。这一方法背后的前提是 , 一个对象的构造器能够从另一个对象中继承方法,建立起一个原型对象,所有的新的对象都将从这个原型创建。
function Person( name ) { this.name = name;}Person.prototype.getName = function() { return this.name;};function User( name, password ) {
this.name = name; this.password = password;};User.prototype = new Person();User.prototype.getPassword = function() { return this.password;};
Function
类继承
Object.extend = function(destination, source) { for (property in source) { destination[property] = source[property]; } return destination;
} Object.extend(String.prototype,{
trim:function() { return this.replace(/(^\s*)|(\s*$)/g, '');
}
});“ flashfget ”.trim(); //”flashget”
Function
function create() { var counter = 0; this.pi = 3.14;return {
increment: function() { counter++;return counter ;}, print: function() { console.log(counter); }
} } var c = create(); c.increment(); c.[“print”](); // 1
Function
Prototype 和属性在 javascript 里是先通过属性查找值,然后通过 prototype 查找值。
function Circle(r) { this.r = r;
}Circle.prototype.PI = 3.14; Circle.prototype.Area = function(){return this.PI * this.r * this.r};var c = new Circle(1);console.log(c.Area()); //3.14var d = new Circle(1);d.PI = 4;console.log(d.Area()); //4
Function结合以上概念我们可以编写 AOP 的程序if(!flashget){var flashget={};
(function(){ function e(c,a){
var b=c.split(/\./);var d=window;for(var e=0;e<b.length-1;e++){
d=d[b[e]]}d[b[b.length-1]]=a
} function c(f){
window.onload = f;} e("flashget.callBack",c); e("symbolTable",e);
})()}flashget.callBack(function(){alert(‘window.onload’)})
Function
function User( properties ) { for ( var i in properties ) {
(function(which){ var p= i;which[ "get" + i ] = function() {return properties[p]; }; which[ "set" + i ] = function(val) {properties[p] = val; }; })(this);
}}var user = new User({ name: "Bob", age: 44});console.log( user.name == null );console.log( user.getname() == "Bob" );user.setage( 22 );console.log( user.getage() == 22 );
Function错误的代码:function User( properties ) {
for ( var i in properties ) { (function(){
this[ "get" + i ] = function() { return properties[i]; }; this[ "set" + i ] = function(val) { properties[i] = val; }; })();
}} 有谁能指出错在哪儿?
Thank you for listening!