JavaScript高级
一、对象
1、访问对象属性的语法是:objectName.propertyName
2、调用对象方法的语法是:objectName.methodName()
3、创建JavaScript对象
(1)定义并创建对象的实例
<span style="font-family:KaiTi_GB2312;font-size:14px;"><!DOCTYPE html>
<html>
<body>
<script>
var person=new Object();//创建直接的实例
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
document.write(person.firstname + " is " + person.age + " years old.");
//简易的创建直接实例
student={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"}
document.write("<br>"+student.lastname + " is " +student.age + " years old.");
</script>
</body>
</html></span>
(2)使用函数来定义对象,然后创建新的对象实例
<span style="font-family:KaiTi_GB2312;font-size:14px;"><!DOCTYPE html>
<html>
<body>
<script>
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
myFather=new person("John","Doe",50,"blue");
document.write(myFather.firstname + " is " + myFather.age + " years old.");
</script>
</body>
</html></span>
4、把方法添加到JavaScript
<span style="font-family:KaiTi_GB2312;font-size:14px;"><!DOCTYPE html>
<html>
<body>
<script>
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.changeName=changeName;
<span style="color:#ff0000;">function changeName(name)
{
this.lastname=name;
}</span>
}
myMother=new person("Sally","Rally",48,"green");
<span style="color:#ff0000;">myMother.changeName("Doe");</span>
document.write(myMother.lastname);
</script>
</body>
</html></span>
二、JavaScript的闭包
<!DOCTYPE html>
<html>
<body>
<p>局部变量计数。</p>
<button type="button" οnclick="myFunction()">计数!</button>
<p id="demo">0</p>
<script>
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
//先return一个值,再把值赋值为0
function myFunction(){
document.getElementById("demo").innerHTML = add();
}
</script>
</body>
</html>