JavaScript高级

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>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值