JavaScript The Definitive Guide 5th Edition [摘录]

原贴地址:http://blog.csdn.net/smartkernel/archive/2007/07/28/1713094.aspx

www.SmartKernel.com

【书名 】:JavaScript The Definitive Guide 5th Edition
【出版社 】:O'Reilly
【作者 】:David Flanagan
【评价 】:★★★★★★★☆☆☆
【正文 】:

----------------------------------------------------------------------------------------------------
0001:
JavaScript使用Unicode字符集。
----------------------------------------------------------------------------------------------------
0002:
进制的问题:下面代码输出18
var a = 03;
var b = 017;
document.write(a+b);
----------------------------------------------------------------------------------------------------
0003:
枚举的使用:
var point = { x:2.3, y:-1.2 };
document.write(point.x+"|"+point.y);
----------------------------------------------------------------------------------------------------
0004:
声明数组的方法:
var myArray = [1,2,3,4,5];
for(i = 0;i < myArray.length;i++)
{
document.write(myArray[i]+"<br>");
}
----------------------------------------------------------------------------------------------------
0005:
Date的特别说明:
var xmas = new Date(2006, 11, 25);
document.write(xmas.toLocaleString());//输出2006年12月25日 0:00:00,月份是从0开始的
----------------------------------------------------------------------------------------------------
0006:
传值调用:Numbers,booleans
传引用调用:Objects,Arrays,functions

Strings类似于C#中,也是不变类型
var s1 = "hello";
var s2 = "hell" + "o";
if (s1 == s2)
{
document.write("Strings按值比较");
}
----------------------------------------------------------------------------------------------------
0007:
函数里面能嵌套函数:
function fun1()
{
function fun2()
{
document.write("-------------");
}
fun2();
}
fun1();
----------------------------------------------------------------------------------------------------
0008:
global对象:在JavaScript代码运行前将先创建global对象,此对象保存着所有全局变量,函数等的引用。可
以使用this引用global对象。
<script language="JavaScript">
var i = "10";
document.write(this.i+"<br>");
document.write(this.Math.E+"<br>");
</script>
----------------------------------------------------------------------------------------------------
0009:
抛出异常:throw new Error("------------");
----------------------------------------------------------------------------------------------------
0010:
判断属性是否存在:也可以使用hasOwnProperty
var myArray = new Array();
if("length" in myArray)
{
document.write("存在这个属性");
}
----------------------------------------------------------------------------------------------------
0011:
对象的constructor属性:
var d = new Date();
if(d.constructor == Date)
{
document.write("这个属性是构造函数的引用");
}

这个属性可以用来判断一个对象的类型:
function fun(o)
{
if((typeof(o) == "object") && (o.constructor == Date))
{
document.write(o.toLocaleString());
}
else
{
document.write("-----------");
}
}
var d = new Date();
try
{
fun(d);
}
catch(err)
{
document.write("异常");
}
----------------------------------------------------------------------------------------------------
0012:
function对象的callee属性:
function fun(x)
{
if (x <= 1)
{
return 1;
}
return x * arguments.callee(x-1);
}
document.write(fun(5));
----------------------------------------------------------------------------------------------------
0013:
声明一个类:
function Rectangle(w, h)
{
this.width = w;
this.height = h;
this.area = function()
{
return this.width * this.height;
}
}
var aRectangle = new Rectangle(20,10);
document.write(aRectangle.area());
----------------------------------------------------------------------------------------------------
0014:
prototype中的属性和直接的属性有先后的执行顺序。首先寻找直接属性,如果直接属性不存在,进一步寻找
prototype中的属性。如果直接属性存在,则不再进一步寻找prototype中的属性。利用这个特点就能实现类的继承。
function Rectangle(w, h)
{
this.width = w;
this.height = h;
this.area = function()
{
return this.width * this.height;
}
}
Rectangle.prototype.area = function()
{
return "面积是:"+this.width * this.height;
}
Rectangle.prototype.say = function()
{
return "-------------------";
}

var aRectangle = new Rectangle(20,10);
document.write(aRectangle.area());
document.write("<br>"+aRectangle.say());
----------------------------------------------------------------------------------------------------
0015:
Object.prototype不要进行扩展,扩展这个属性会引起比较复杂的错误逻辑。
----------------------------------------------------------------------------------------------------
0016:
捕获全局异常信息:调试的时候很有用
window.onerror = function(err)
{
document.write("<br>--------------------------------------------------------------<br>");
document.write("异常信息:"+err);
document.write("<br>--------------------------------------------------------------<br>");
}
----------------------------------------------------------------------------------------------------
0017:
静态属性和静态方法:
function ToolKit()
{

}
ToolKit.Name = "工具箱类";
ToolKit.Say = function(str)
{
document.write(str);
}
ToolKit.Say(ToolKit.Name);
----------------------------------------------------------------------------------------------------
0018:
一个很好的例子:类
window.onerror = function(err)
{
document.write("<br>--------------------------------------------------------------<br>");
document.write("异常信息:"+err);
document.write("<br>--------------------------------------------------------------<br>");
}
function Circle(radius)
{
this.r = radius;
}
Circle.PI = 3.14159;
Circle.prototype.Area = function( )
{
return Circle.PI * this.r * this.r;
}
Circle.Max = function(a,b)
{
if (a.r > b.r)
{
return a;
}
else
{
return b;
}
}
var aCircle = new Circle(1.0);
var bCircle = new Circle(2.0);
var cCircle = Circle.Max(aCircle,bCircle);
document.write(cCircle.Area());
----------------------------------------------------------------------------------------------------
0019:
私有属性:不再直接保存属性就可以了
function Person(name)
{
this.GetName = function()
{
return "我是:"+name;
}
}
Person.prototype.Say = function()
{
document.write(this.GetName());
}
var aPerson = new Person("小王");
aPerson.Say();
----------------------------------------------------------------------------------------------------
0020:
继承关系的例子:
function Rectangle(w, h, n)
{
this.Width = w;
this.Height = h;
this.Name = n;
}
Rectangle.prototype.Area = function( ) { return this.Width * this.Height; }


function PositionedRectangle(x, y, w, h, n)
{
//调用基类的构造函数
Rectangle.call(this, w, h, n);
this.x = x;
this.y = y;
}
//获得基类的属性和方法
PositionedRectangle.prototype = new Rectangle( );
//删除不需要的,从基类继承的属性(好像删除了还可以访问?)
delete PositionedRectangle.prototype.Width;
delete PositionedRectangle.prototype.Height;
PositionedRectangle.prototype.constructor = PositionedRectangle;
PositionedRectangle.prototype.Contains = function(x,y)
{
return true;
}


var aPositionedRectangle = new PositionedRectangle(100,100,20,20,"A区域");

document.write(aPositionedRectangle.Area()+"<br>");
document.write(aPositionedRectangle.Name+"<br>");
document.write(aPositionedRectangle.Contains(123,123)+"<br>");
----------------------------------------------------------------------------------------------------
0021:
函数内部声明的方法外部不能访问:甚至除了外层大括号以外的任何地方,即使是对象的声明
function FunOut()
{
function FunIn()
{
document.write("内部函数!"+"<br>");
}
}
----------------------------------------------------------------------------------------------------
0022:
print();//调用打印页面对话框
----------------------------------------------------------------------------------------------------
0023:
继承的另外一种写法:注意基类构造函数调用方法
function Person(name)
{
this.Name = name;
}
function NewPerson(name)
{
this.superclass(name);
}
NewPerson.prototype.superclass = Person;

var aNewPerson = new NewPerson("小王");
document.write(aNewPerson.Name);
----------------------------------------------------------------------------------------------------
0024:
覆盖基类的方法:
function Person(name)
{
this.Name = name;
}
Person.prototype.Say = function()
{
document.write(this.Name);
}

function NewPerson(name)
{
this.superclass(name);
}
NewPerson.prototype.superclass = Person;
NewPerson.prototype.Say = function()
{
document.write("我是:"+this.Name);
}

var aNewPerson = new NewPerson("小王");
aNewPerson.Say();
----------------------------------------------------------------------------------------------------
0025:
命名空间的使用:
var Solosecond = {}

Solosecond.Form = {}

Solosecond.Form.Fun = function()
{
document.write("Fun被调用了");
}

Solosecond.Form.Fun();
----------------------------------------------------------------------------------------------------
0026:
一个多层命名空间下声明类的使用:
var Solosecond = {Windows:{Form:{Control:{}}}}

Solosecond.Windows.Form.Control.Label = function(name)
{
this.Name = name;
}
Solosecond.Windows.Form.Control.Label.prototype.Say = function()
{
document.write(this.Name);
}

var aLabel = new Solosecond.Windows.Form.Control.Label("aLabel");
aLabel.Say();
----------------------------------------------------------------------------------------------------
0027:
正则表达式相关:

正则表达式的对象使用/.../来声明:var pattern = /s$/;或者var pattern = new RegExp("s$");

/s$/:以s结尾的字符串
/s/:字符串中包含s
[abc]:任何包含a、b、c的字符串
[^abc]:任何不包含a、b、c的字符串
.:任何字符
\w:[a-zA-Z0-9_]
\W:[^a-zA-Z0-9_]
\s:任何Unicode字符
\S:任何非Unicode字符
\d:[0-9]
\D:[^0-9]
[\b]:空格
{n,m}:之前的字符重复n到m次之间
{n,}:之前的字符重复n次以上
{n}:之前的字符重复n次
?:之前的字符是可选的,{0,1}
+:之前的字符重复1次以上,{1,}
*:之前的字符是可选或重复多少次,{0,}
^:以什么开头的
$:以什么结尾的

i:区分大小写

|:左边的表达式或者右边的表达式都可以
(...):将表达式分组

var pattern = /Java/g;
var text = "JavaScript is more fun than Java!";
var result;
while((result = pattern.exec(text)) != null)
{
alert("Matched '" + result[0] + "'" +" at position " + result.index
+"; next search begins at " + pattern.lastIndex);
}
----------------------------------------------------------------------------------------------------
0028:
<input type="checkbox" onclick="if(this.checked){alert('选择了');}else{alert('取消选择了')}" />
<a href="JavaScript:alert('单击了')">联接</a>
----------------------------------------------------------------------------------------------------
0029:
JavaScript是单线程机制的。
----------------------------------------------------------------------------------------------------
0030:
JavaScript没有操纵客户端文件的功能。
----------------------------------------------------------------------------------------------------
0031:
从传递过来的字符串中查询参数:
function getArgs( )
{
var args = new Object( );
var query = location.search.substring(1);
var pairs = query.split("&");
for(var i = 0; i < pairs.length; i++)
{
var pos = pairs[i].indexOf('=');
if (pos == -1)
{
continue;
}
var argname = pairs[i].substring(0,pos);
var value = pairs[i].substring(pos+1);
value = decodeURIComponent(value);
args[argname] = value;
}
return args;
}
----------------------------------------------------------------------------------------------------
0032:
获得客户端的浏览器的信息:
var browser = "BROWSER INFORMATION:\n";
for(var propname in navigator)
{
browser += propname + ": " + navigator[propname] + "\n"
}
alert(browser);
----------------------------------------------------------------------------------------------------
0033:
setInterval的使用:每隔固定时间就运行一次
<script>
var myTimer = null;
function startFun()
{
function fun()
{
var myDate = new Date();
var myTime = document.getElementById("myTime");
myTime.value = myDate.toLocaleTimeString();//这里不要使用document.write来显式
}
myTimer = setInterval(fun,100);
}
function endFun()
{
clearInterval(myTimer);
}
</script>
<input type="text" id="myTime" />

<button onclick="startFun( )">Start</button>
<button onclick="endFun( )">End</button>
----------------------------------------------------------------------------------------------------
0034:
<script>
function Fun()
{
var isConfirm = window.confirm("确定打开么?");
if(isConfirm == true)
{
alert("打开了!");
}
else
{
alert("撤销了!");
}
}
</script>

<button onclick="Fun( )">打开</button>
----------------------------------------------------------------------------------------------------
0035:
异常信息的处理:onerror
window.onerror = function(err, url, line)
{
document.write("--------------------------------------------------------------<br>");
document.write("异常信息:"+err+"<br>");
document.write("联接地址:"+url+"<br>");
document.write("所在行数:"+line);
document.write("<br>--------------------------------------------------------------<br>");
}
----------------------------------------------------------------------------------------------------
0036:
使用DOM模型遍历页面是元素的对象:
for(var i =0;i < document.documentElement.childNodes.length;i++)
{
if(document.documentElement.childNodes[i].nodeType == 1/*Node.ELEMENT_NODE*/)
{
document.write(document.documentElement.childNodes[i].tagName+"<br>");
}
}
----------------------------------------------------------------------------------------------------
0037:
获得页面元素引用的几种方式:
var aBody = document.getElementById("myBody");
var bBody = document.body;
var cBody = document.getElementsByTagName("body")[0];//返回的是数组
----------------------------------------------------------------------------------------------------
0038:
操纵DOM元素的例子:
<script>
function sortkids(e)
{
if (typeof e == "string")
{
e = document.getElementById(e);
}
var kids = [];
if (x.nodeType == 1 /* Node.ELEMENT_NODE */)
{
kids.push(x);
x.firstChild.data = x.firstChild.data.toUpperCase();
}

kids.sort
(
function(n, m)
{
var s = n.firstChild.data;
var t = m.firstChild.data;
if (s < t) {return -1;}
else if (s > t) {return 1;}
else {return 0;}
}
);
for(var i = 0; i < kids.length; i++) e.appendChild(kids[i]);
}
</script>
<ul id="list">
<li>one
<li>two
<li>three
<li>four
</ul>
<button onclick="sortkids('list')">Sort list</button>
----------------------------------------------------------------------------------------------------
0039:
用DOM元素增加HTML页面元素:
var ele = document.createElement("button");
ele.setAttribute("value","按钮");//ele.value = "按钮";
ele.style.height = ele.style.width = 50;
document.body.appendChild(ele);
----------------------------------------------------------------------------------------------------
0040:
IE中,对象元素注册事件的方法:
<div id="myDiv" style="width:200; height:200; background-color:Gray;"></div>
<script>
function MouseoverFun()
{
window.defaultStatus = event.x;
}
var myDiv = document.getElementById("myDiv");
myDiv.attachEvent("onmouseover", MouseoverFun);
</script>
----------------------------------------------------------------------------------------------------
0041:
拖动窗口:
<script language="JavaScript">
function drag(elementToDrag, myevent)
{

var startX = myevent.clientX, startY = myevent.clientY;
var origX = elementToDrag.offsetLeft, origY = elementToDrag.offsetTop;
var deltaX = startX - origX, deltaY = startY - origY;

elementToDrag.setCapture( );
elementToDrag.attachEvent("onmousemove", moveHandler);
elementToDrag.attachEvent("onmouseup", upHandler);
elementToDrag.attachEvent("onlosecapture", upHandler);

if (myevent.stopPropagation)
{
myevent.stopPropagation( );
}
else
{
myevent.cancelBubble = true;
}
if (myevent.preventDefault)
{
myevent.preventDefault( );
}
else
{
myevent.returnValue = false;
}
function moveHandler()
{
var e = window.event;
elementToDrag.style.left = (e.clientX - deltaX) + "px";
elementToDrag.style.top = (e.clientY - deltaY) + "px";
if (e.stopPropagation)
{
e.stopPropagation( );
}
else
{
e.cancelBubble = true;
}
}
function upHandler()
{
var e = window.event;

elementToDrag.detachEvent("onlosecapture", upHandler);
elementToDrag.detachEvent("onmouseup", upHandler);
elementToDrag.detachEvent("onmousemove", moveHandler);
elementToDrag.releaseCapture( );

if (e.stopPropagation)
{
e.stopPropagation( );
}
else
{
e.cancelBubble = true;
}
}
}
</script>
<div style="position:absolute; left:100px; top:100px; width:250px; height:250px;white; border: solid black;">
<div style="background-color: gray;height:20px; border-bottom: solid;" onmousedown="drag(this.parentNode, event);">
<p>拖动窗口</p>
</div>
<p>&nbsp;●.....................</p>
<p>&nbsp;●.....................</p>
<p>&nbsp;●.....................</p>
<p>&nbsp;●.....................</p>
</div>
----------------------------------------------------------------------------------------------------
0042:
XMLHttpRequest异步请求的一个小例子:
<script language="JavaScript">
var HTTP = [];
HTTP._factories =
[
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];

HTTP._factory = null;
HTTP.newRequest = function()
{
if (HTTP._factory != null)
{
return HTTP._factory();
}
for(var i = 0; i < HTTP._factories.length; i++)
{
try
{
var factory = HTTP._factories[i];
var request = factory();
if (request != null)
{
HTTP._factory = factory;
return request;
}
}
catch(e)
{
continue;
}
}
HTTP._factory = function()
{
throw new Error("XMLHttpRequest not supported");
}
HTTP._factory();
}
function fun()
{
var request = HTTP.newRequest();
request.onreadystatechange = function()
{
if (request.readyState == 4/*finished*/)
{
if(request.status == 200/*successful*/)
{
alert(request.responseText);
}
}
}
//异步调用
request.open("GET","open.htm",true);
request.send(null);
}
</script>
<input type="button" value="XMLHttpRequest" onclick="fun()"/>
----------------------------------------------------------------------------------------------------
0043:
XMLHttpRequest的几个通用方法:
var HTTP = [];
//请求文本
HTTP.getText = function(url, callback)
{
var request = HTTP.newRequest();
request.onreadystatechange = function()
{
if (request.readyState == 4 && request.status == 200)
{
callback(request.responseText);
}
}
request.open("GET", url);
request.send(null);
}
HTTP.getXML = function(url, callback)
{
var request = HTTP.newRequest();
request.onreadystatechange = function()
{
if (request.readyState == 4 && request.status == 200)
{
callback(request.responseXML);
}
}
request.open("GET", url);
request.send(null);
}
----------------------------------------------------------------------------------------------------

你可能感兴趣的:(JavaScript,windows,正则表达式,prototype,出版)