object
javascript也是面向对象的语言,与其他的面向对象语言例如C++类似。每个对象包含的变量称为property,函数则成为method。
constructor
构造函数也与c++类似,this表示对象本身
function Blog(who, what, when, where){
this.who = who;
...
}
声明对象的时候用new:
var blogEntry = new Blog(...);
创建一个Blog对象
<html>
<head>
<title>YouCube - The Blog for Cube Puzzlers</title>
<script type="text/javascript">
// Blog object constructor
function Blog(body, date) {
// Assign the properties
this.body = body;
this.date = date;
}
// Global array of blog entries
var blog = [ new Blog("Got the new cube I ordered. It's a real pearl.", "08/14/2008"),
new Blog("Solved the new cube but of course, now I'm bored and shopping for a new one.", "08/19/2008"),
new Blog("Managed to get a headache toiling over the new cube. Gotta nap.", "08/16/2008"),
new Blog("Found a 7x7x7 cube for sale online. Yikes! That one could be a beast.", "08/21/2008") ];
// Show the list of blog entries
function showBlog(numEntries) {
// Adjust the number of entries to show the full blog, if necessary
if (!numEntries)
numEntries = blog.length;
// Show the blog entries
var i = 0, blogText = "";
while (i < blog.length && i < numEntries) {
// Use a gray background for every other blog entry
if (i % 2 == 0)
blogText += "<p style='background-color:#EEEEEE'>";
else
blogText += "<p>";
// Generate the formatted blog HTML code
blogText += "<strong>" + blog[i].date + "</strong><br />" + blog[i].body + "</p>";
i++;
}
// Set the blog HTML code on the page
document.getElementById("blog").innerHTML = blogText;
}
</script>
</head>
<body onload="showBlog(5);">
<h3>YouCube - The Blog for Cube Puzzlers</h3>
<img src="cube.png" alt="YouCube" />
<div id="blog"></div>
<input type="button" id="showall" value="Show All Blog Entries" onclick="showBlog();" />
</body>
</html>
很明显上面代码创建了4个Blog对象,直接用了innerHTML的方式修改<div>里面的内容。上面的博客内容只是简单排列,下面增加一个按照日期排序显示的功能,由于上面的日期只是字符串的形式,为了排序需要转化为更加具体的时间,需要用到一些自带的函数:
- setMonth()
- setYear()
- getDate()
- getDay()
- getFullYear()
为了比较两个日期的大小,加入以下函数:
function getDaysBetween(date1, date2){
var daysBetween = (date2 - date1) / (1000 * 60 * 60 * 24);//毫秒转化为天 return Math.round(daysBetween);
}
Date
在构建Blog对象的时候,日期的输入格式是字符串,我们可以用自带的Date()函数创建日期对象作为输入参数:
var blog = [ new Blog('...', new Date('08/14/2008')),
...
];
toString()
toString()函数可以把一个对象变成字符串的表示
var blogDate = new Date('08/08/2008');
alert(blogDate.toString());
sort
数组对象本身也提供了排序的函数,可以给sort一个比较函数的参数来设置排序的方式:
function compare(x, y){
return x - y;
}
nums.sort(compare);
如果x < y,compare返回负值,排序后x会在y的前面。日期大的博客要显示在前面,比较函数比较简单可以不用给它命名,类似于python的匿名函数:
blog.sort(function(blog1, blog2){
return blog2.date - blog1.date;
});
indexOf() : 在字符串中搜索子字符串,返回子字符串首字母出现的下标位置
var str = 'i love this game';
alert(str.indexOf('love');
> 2
还有一些用于字符串搜索的函数:
- charAt() : 搜索单个字符的位置
- toLowerCase()
- toUpperCase()
Math
Math对象包含一些常用的数学函数,包括常数PI,产生随机数等
- PI
- round()
- floor()
- ceil()
- random() : 0 ~ 1内的随机小数
Object Oriented
javascript是面向对象的语言,处理数据一般可以把数据封装在对象里面,如果和对象里面的某些数据的处理联系紧密的功能则可以成为对象的一个method,这样做不仅可以使数据的处理逻辑更加鲜明,也简化了代码和增加了代码的复用。