现代的JavaScript
JavaScript语言一直在稳步发展。JavaScript给人的印象已经从一门简单如玩具一般的语言演变到备受尊敬的编程语言,世界上众多公司和开发者都用它构造出种种不可思议的应用程序。现代的JavaScript编程语言一如既往地牢固、健壮,功能强大到令人难以置信的地步。1. 面向对象的JavaScript
JavaScript一开始被设计成一门彻底的面向对象语言,面向对象的JavaScript代码和其它具有对象特性的语言稍有不同,用简单的示例说明下:
[code lang="js"]
// 'Lecture'类的构造函数
// 用名称(name)和 (teacher)作为参数
function Lecture( name, teacher ) {
// 将参数保存为对象的局部属性
this.name = name;
this.teacher = teacher;
}
// Lecture类的一个方法(method),用于生成一条显示Lecture信息的字符串
Lecture.prototype.display = function(){
return this.teacher + " is teaching " + this.name;
};
// Schedule类的构造函数,以课程的数组作为参数
function Schedule( lectures ) {
this.lectures = lectures;
}
// 构造一条字符串,标识课程的安排表
Schedule.prototype.display = function(){
var str = "";
// 遍历每项课程,建立包含它们信息的字符串
for ( var i = 0; i < this.lectures.length; i++ )
str += this.lectures[i].display() + " ";
return str;
};
[/code]
2. DOM
DOM是表达XML文档的常见方式,大部分Web开发的编程语言(如Java、Perl、PHP、Python等)都提供了相应的实现。DOM给开发者提供了一种定位XML层级结构的直观方法。
[code lang="js"]
Introduction to the DOM
// 必须在加载完成后才操作DOM
window.onload = function(){
// 获取文档中所有的
var li = document.getElementsByTagName('li');
// 并给它们全部添加一个黑色边框
for ( var j = 0; j < li.length; j++ ) {
li[j].style.border = '1px solid #000';
}
// 获取id为'everywhere'的元素
var every = document.getElementById( "everywhere" );
// 从文档中删除这个元素
every.parentNode.removeChild( every );
};
Introduction to the DOM
There are a number of reasons why the DOM is awesome, here are some:
- It can be found everywhere.
- It's easy to use.
- It can help you to find what you want, really quickly.
[/code]
3. 事件
事件(Event)是黏合应用程序中所有用户交互的胶水。在设计良好的JavaScript应用程序中,既有数据来源,又有这些数据的视觉表现(在HTML DOM中的表现),要在这两个方面之间进行同步就必须通过与用户交互,并据此来更新用户界面。DOM和JavaScript事件的组合,是决定所有现代Web应用程序形态的根本所在。
[code lang="js"]
Introduction to the DOM
// 必须在加载完成后才操作DOM
window.onload = function(){
// 获取文档中所有的
var li = document.getElementsByTagName('li');
for ( var i = 0; i < li.length; i++ ) {
// 给这个
// 它将这个
li[i].onmouseover = function() {
this.style.backgroundColor = 'blue';
};
// 给这个
// 将它的背景颜色重置为默认的白色
li[i].onmouseout = function() {
this.style.backgroundColor = 'white';
};
}
};
Introduction to the DOM
There are a number of reasons why the DOM is awesome, here are some:
- It can be found everywhere.
- It's easy to use.
- It can help you to find what you want, really quickly.
[/code]
<img src="http://www.everyinch.net/wp-content/uploads/2013/11/funnyjavascript.gif" alt="funnyjavascript" width="400" height="267" class="alignnone size-full wp-image-3514" />
查看完整版本: 现代的JavaScript
Tags: JavaScript概述