SlideShare a Scribd company logo
Javascript  基础和进阶 数据类型篇 马士华
Javascript 简介 JavaScript 是一种轻型的解释型的程序语言。 JavaScript 最开始就是被设计成一种彻底的面向对象语言。
如何调试脚本 调试 js 脚本推荐使用 Firebug  console Firebug 提供了许多的有用的工具,如错误控制台, 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 引号的用法: &quot;You make 'me' sad.“ 'Holy &quot;cranking&quot; moses!'  &quot;<a href=\&quot;home\&quot;>Home</a>&quot;
String 方法: &quot;hello&quot;.charAt(0) // &quot;h&quot;  &quot;hello&quot;.toUpperCase() // &quot;HELLO&quot;  &quot;Hello&quot;.toLowerCase() // &quot;hello&quot;  &quot;hello&quot;.replace(/e|o/g, &quot;x&quot;) // &quot;hxllx&quot;  &quot;1,2,3&quot;.split(&quot;,&quot;) // [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;]  “ hello&quot;. substring(1,4) //ell “ hello&quot;. substr(1,2) //el “ hello&quot;. Indexof(‘e’,0) //1 “ hello&quot;.lastIndexof(‘l’,’hello’.length-1) //3
String 长度属性: &quot;Hello&quot;.length // 5  &quot;&quot;.length // 0  默认的 Boolean 属性: !&quot;&quot; // true   !&quot;hello&quot; // false
Number Javascript 并不区分整形和浮点,所有的数字都用浮点来表示( IEEE754 标准的浮点格式,即 double )。 例子: 123 , 123.68 typeof 123 // &quot;number&quot;  typeof 123.68// &quot;number&quot;  运算符: 所有的 C 语言中对数字的运算符 (+, -, *, /, %, =, +=, -=, *=, /=, ++, --)
Number 默认的 Boolean 属性: !0 // true   !1 // false   !-1 // false  parseInt & parseFloat parseInt(&quot;123&quot;) = 123 (implicit decimal) parseInt(&quot;010&quot;) = 8 (implicit octal)  parseInt(&quot;010&quot;, 10) = 10 (explicit decimal) parseInt(&quot;11&quot;, 2) = 3 (explicit binary) parseFloat(&quot;10.10&quot;) = 10.1
Number Numbers to Strings &quot;&quot; + 1 + 2; // &quot;12&quot;  &quot;&quot; + (1 + 2); // &quot;3&quot;  NaN & Infinity parseInt(&quot;hello&quot;, 10) // NaN isNaN(parseInt(&quot;hello&quot;, 10)) // true 1 / 0 // Infinity  typeof NaN // &quot;number&quot;  typeof Infinity // &quot;number&quot;
Boolean Boolean  只有 true 和 false 的值 if ( true ) console.log(&quot;always!&quot;)  if ( false ) console.log(&quot;never print!&quot;)  运算符: & || true & true //true true & false //false true || false //true false || false //false
|| 运用 || 运算符可以产生短路现象: var t,y,x=0,z=1,w={} ; var c = t || 0;  //now c=0  var c = t || y || 0;  //now c=0 var 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=1 var c = t || y || w || t || 0;  //now c=w
Object 在 Javascript 中任何东西都是 Object. 下面是 Object 的表达式。 var x = {};  var y = { name: &quot;Pete&quot;,  age: 15 }; typeof {} // &quot;object&quot;
Object . 符号: 用 . 符号读取和写入 Object 的属性。 y.name // &quot;Pete&quot;  y.age // 15  x.name = y.name + &quot; Pan&quot; // &quot;Pete Pan x.age = y.age + 1 // 16
Object [] 符号 也可用 Array 的符号 [] 操作。 var operations = {  increase: &quot;++&quot;, decrease: &quot;--“ }  var operation = &quot;increase&quot;; operations[operation] // &quot;++&quot;; operations[&quot;multiply&quot;] = &quot;*&quot;; // &quot;*&quot;  x [&quot; age &quot;]  //16
Object 遍历: var obj = { name: &quot;Pete&quot;, age: 15 };  for(key in obj) { console.log(&quot;key=&quot; + key, &quot;value=&quot;+obj[key]);  }  // &quot;key=name&quot;, &quot;value=Pete&quot;  // &quot;key=age&quot;, &quot;value=15&quot;  默认的 Boolean 属性 : !{} //false
Array 例子: var x = [];  var y = [1, 2, 3]; typeof []; // &quot;object&quot;  typeof [1, 2, 3]; // &quot;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(&quot; – &quot;) // &quot;2 - 1 - 3 - 0&quot;  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  和 constructor if ( typeof num == &quot;string&quot; ) num = parseInt( num ); if ( typeof arr == &quot;string&quot; ) arr = arr.split(&quot;,&quot;); if ( num.constructor == String ) num = parseInt( num ); if ( str.constructor == Array ) str = str.join(','); 变量类型检查   ———————————————————————————————    Variable       typeof Variable    Variable.constructor   ———————————————————————————————    {an:&quot;object&quot;}    “ object”         Object    [&quot;an&quot;,&quot;array&quot;]     “ object”         Array    function(){}     “ function”        Function    &quot;a string&quot;       “ 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(); // &quot;undefined&quot;, 0 log(1); // &quot;number&quot;, 1 log(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;); // &quot;string&quot;, 3
Function Call and Apply 我们同样可以指定上下文到 function 通过 call 和 apply 方法,唯一不同的是 call 的参数必须是 Array 或 Arguments 对象。 Apply 接受 array 为 Arguments 。 function scope() {  console.log(this, arguments.length);  }  scope() // window, 0  scope.call(&quot;foobar&quot;, [1,2]); // &quot;foobar&quot;, 1 scope.apply(&quot;foobar&quot;, [1,2]); // &quot;foobar&quot;, 2
Function Context 在 javascript 中, this 总是指导当前的上下文。默认是 window 对象。 var flashget=“flashget” console.log(window.flashget) // “flashget” 下面的例子, this 指到 id 为 t 的元素中去了 Object.prototype.getHTML =function(){  if(this['nodeName']) console.log(this.innerHTML); } document.getElementById(&quot;t&quot;). getHTML();
Function 改变函数上下文的示例   function changeColor( color ) { this.style.color = color; } //wrong,because window desn't hava style attribute changeColor( &quot;white&quot; ); var main = document.getElementById(&quot;main&quot;); changeColor.call( main, &quot;black&quot; ); function setBodyColor() { changeColor.apply( document.body, arguments ); } setBodyColor( &quot;black&quot; );
Function Scope (作用域) 作用域是 JavaScript 中一个较难处理的特性。所有面向对象的编程语言都有某种形式的作用域;这要看是什么上下文约束着作用域。在 JavaScript 里,作用域由函数约束,而不由块约束 ( 如 while,if, 和 for 里的语句体 ) 。 var v = &quot;globe&quot;; function scope() { console.log(v)  //undefined var v = &quot;in a function“;  console.log(v);  //in a function } scope()  console.log(v) //globe
Function 虽然在全局变量中可以不使用 var ,但是在局部变量中一定要使用 var ,下面代码可以说明问题。 var v = &quot;globe&quot;; function scope() { console.log(v);   // globe v = &quot;in a function&quot;  console.log(v);   // in a function m = &quot;in a function define a globe“ } scope()  console.log(v) //in a function console.log(m) // in a function define a globe
Function Closures (闭包) 闭包意味着内层的函数可以引用存在于包绕它的函数的变量,即使外层的函数的执行已经终止。 也意味着内层的函数可以创建外面不可访问的变量和方法。 var obj = document.getElementById(&quot;main&quot;); obj.style.border = &quot;1px solid red&quot;; setTimeout(function(){     obj.style.display = 'none'; }, 1000); function delayedAlert( msg, time ) {     setTimeout(function(){         alert( msg );     }, time ); } delayedAlert( &quot;Welcome!&quot;, 2000 );
Function Closures (闭包) 使用匿名函数激发一个创建多个闭包函数所需的作用域的例子  : var items = document.getElementsByTagName(&quot;a&quot;); for ( var i = 0,item; item = items[i]; i++ ){  (function(){  var href = item.getAttribute(&quot;href&quot;);  item[&quot;onclick&quot;] = function(){  console.log( href );  return false;  };  })();    item.setAttribute(&quot;href&quot;,&quot;#&quot;);  }
Function Closures (闭包) 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, &quot;doOnClick&quot;);  el.onmouseover = associateObjWithEvent(this, &quot;doMouseOver&quot;);  el.onmouseout = associateObjWithEvent(this, &quot;doMouseOut&quot;);  } } 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.}
Function Reference (引用) JavaScript 的一个重要的方面是引用的概念。引用就是指向对象实际位置的指针。这是一项极其强大的功能。引用总是只指向最终被引用的对象,而不会是引用本身。  Number , Boolean , null 和为定义的值为基本类型。对象,数组,函数为引用类型。 var obj = new Object(); var objRef = obj; obj.oneProperty = true; console.log( obj.oneProperty === objRef.oneProperty ); //true var items = new Array( &quot;one&quot;, &quot;two&quot;, &quot;three&quot; ); var itemsRef = items; items.push( &quot;four&quot; ); console.log( items.length == itemsRef.length ); //true var items = new Array( &quot;one&quot;, &quot;two&quot;, &quot;three&quot; ); var itemsRef = items; items = new Array( &quot;new&quot;, &quot;array&quot; ); //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( &quot;Hello, World!&quot; ); sendMessage( &quot;How are you?&quot;, { handleMsg: function( msg ) { console.log( &quot;This is a custom message: &quot; + msg ); } });
Function 继承 JavaScript 使用了一种独特的对象创建和继承的方式,称为原型继承( prototypal 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.14 var 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(&quot;flashget.callBack&quot;,c);    e(&quot;symbolTable&quot;,e);  })() } flashget.callBack(function(){alert(‘window.onload’)})
Function function User( properties ) {  for ( var i in properties ) {  (function(which){   var p= i; which[ &quot;get&quot; + i ] = function() {return properties[p]; };  which[ &quot;set&quot; + i ] = function(val) {properties[p] = val;  };  })(this);  } } var user = new User({ name: &quot;Bob&quot;, age: 44}); console.log( user.name == null ); console.log( user.getname() == &quot;Bob&quot; ); user.setage( 22 ); console.log( user.getage() == 22 );
Function 错误的代码: function User( properties ) {  for ( var i in properties ) { (function(){         this[ &quot;get&quot; + i ] = function() {             return properties[i];         };         this[ &quot;set&quot; + i ] = function(val) {             properties[i] = val;         };     })(); } }  有谁能指出错在哪儿?
Thank you for listening !

More Related Content

PDF
Wind.js无障碍调试与排错
PDF
JavaScript现代化排错实践
PDF
The Evolution of Async Programming (GZ TechParty C#)
PPTX
C++11综述/新特性描述/Overview of C++11 New Features
PDF
Vim Hacks
PPT
基于XMPP的Gtalk机器人
PDF
LazyRecord: The Fast ORM for PHP
PDF
深入淺出 Web 容器 - Tomcat 原始碼分析
Wind.js无障碍调试与排错
JavaScript现代化排错实践
The Evolution of Async Programming (GZ TechParty C#)
C++11综述/新特性描述/Overview of C++11 New Features
Vim Hacks
基于XMPP的Gtalk机器人
LazyRecord: The Fast ORM for PHP
深入淺出 Web 容器 - Tomcat 原始碼分析

What's hot (20)

PDF
Introduction to Parse JavaScript SDK
PPTX
PHPUnit + Xdebug 单元测试技术
PDF
functional-scala
PPT
Scala function-and-closures
PDF
Hello Javascript
PPT
Shell脚本
 
PDF
Swift 程序语言介绍
PPT
Introduction to C++ over CLI
PDF
竞赛中C++语言拾遗
PPT
2009 CSBB LAB 新生訓練
PPTX
認識 C++11 新標準及使用 AMP 函式庫作平行運算
PPT
Php extension开发
PPT
iPhone,ios,Object-C基础入门
PPT
第4章函数
PDF
论 Python 与设计模式。
PPT
改善程序设计技术的50个有效做法
PPTX
Js的国(转载)
PPT
页游开发中的 Python 组件与模式
PDF
Compiler for Dummy 一點都不深入的了解 Compiler, Interpreter 和 VM
PPT
ios分享
Introduction to Parse JavaScript SDK
PHPUnit + Xdebug 单元测试技术
functional-scala
Scala function-and-closures
Hello Javascript
Shell脚本
 
Swift 程序语言介绍
Introduction to C++ over CLI
竞赛中C++语言拾遗
2009 CSBB LAB 新生訓練
認識 C++11 新標準及使用 AMP 函式庫作平行運算
Php extension开发
iPhone,ios,Object-C基础入门
第4章函数
论 Python 与设计模式。
改善程序设计技术的50个有效做法
Js的国(转载)
页游开发中的 Python 组件与模式
Compiler for Dummy 一點都不深入的了解 Compiler, Interpreter 和 VM
ios分享
Ad

Viewers also liked (7)

PPTX
If you build it, they will come.
ODP
Fruits Tardor
PPS
Mercedes Benz Muzeum
PPTX
The story of how it all begun [AAMET]
PPT
F2E technique,ability&future
PDF
Sun Valley & Ketchum City Budget Comparison
PPT
Css sprites memory usage
If you build it, they will come.
Fruits Tardor
Mercedes Benz Muzeum
The story of how it all begun [AAMET]
F2E technique,ability&future
Sun Valley & Ketchum City Budget Comparison
Css sprites memory usage
Ad

Similar to Javascript Training (20)

PPT
YUI ─ 阿大
PPT
1 C入門教學
ODP
Ruby程式語言入門導覽
PPT
javascript的分层概念 --- 阿当
PPT
Html5移动web应用开发(PhoneGap)
PPT
Html5移动web应用开发(PhoneGap)
PPT
HTML5移动应用开发分享会(PhoneGap)
PPT
HTML5移动WEB应用程序开发(PhoneGap)
PPT
Vim get start_1.0
PDF
JavaScript 教程
PPT
Python story
PPT
Asp.net mvc 培训
PPT
Python 入门
PDF
Arduino程式快速入門
PPT
iPhone,ios,Object-c基础入门
PPT
Ajax Transportation Methods
PPTX
从问题开始,谈前端架构
DOC
Erlang jiacheng
PPT
Web base 吴志华
PPT
Collaboration On Rails
YUI ─ 阿大
1 C入門教學
Ruby程式語言入門導覽
javascript的分层概念 --- 阿当
Html5移动web应用开发(PhoneGap)
Html5移动web应用开发(PhoneGap)
HTML5移动应用开发分享会(PhoneGap)
HTML5移动WEB应用程序开发(PhoneGap)
Vim get start_1.0
JavaScript 教程
Python story
Asp.net mvc 培训
Python 入门
Arduino程式快速入門
iPhone,ios,Object-c基础入门
Ajax Transportation Methods
从问题开始,谈前端架构
Erlang jiacheng
Web base 吴志华
Collaboration On Rails

Javascript Training

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