javascript的概念
JavaScript是一種可以動態(tài)改變html頁面內(nèi)容的客戶端編程語言。
js的使用
在事件后面直接寫"javascript:js代碼"
使用script標簽,直接寫js代碼
使用script標簽,通過src屬性引入js外部文件
數(shù)據(jù)類型
用var關(guān)鍵字來定義各種數(shù)據(jù)類型的數(shù)據(jù)
var name="lishi";
var age=23;
var study=function(){}
var date=new Date();//不用導(dǎo)包,因為Date是js的內(nèi)置對象
var array=[1,2,3,4];//注意是[],不是{}
小技巧:巧用+或者-來進行字符串與整型之間的轉(zhuǎn)換
例如:
1+"2"="12"; "2"-0=2;
控制流語句
js的控制流語句基本和java一致
例外:foreach循環(huán)
var arr=[12,23,31,42];
for (var index in arr) {
alert(arr[index]);
}
函數(shù)
普通函數(shù)
function 函數(shù)名(){
//函數(shù)體
}
匿名函數(shù)
var 函數(shù)名=function(){
//函數(shù)體
}
動態(tài)函數(shù)
var 函數(shù)名=new Function(){"參數(shù)名","函數(shù)體"}
面向?qū)ο?/h2>
//定義類
function Student(name,age) {
//定義屬性
this.name=name;
this.age=age;
//定義方法
this.study=function(){
alert(this.name+"我正在學習"+this.age);
}
}
//創(chuàng)建對象
var s=new Student("lisi",20);
//獲取屬性
alert(s.name+":"+s.age);
//調(diào)用方法
s.study();
//定義類
function Student(name,age) {
//定義屬性
this.name=name;
this.age=age;
//定義方法
this.study=function(){
alert(this.name+"我正在學習"+this.age);
}
}
//創(chuàng)建對象
var s=new Student("lisi",20);
//獲取屬性
alert(s.name+":"+s.age);
//調(diào)用方法
s.study();
prototype可以理解為java中的繼承,通過這個關(guān)鍵字可以動態(tài)的向類中添加屬性和方法
Student.prototype.sex="男";
Student.prototype.sleep=function(){
alert(this.name+"睡覺");
}