js 对象

 

function Person(name) {

//非静态属性

this.name = name;

//非静态方法

this.show = function() {

alert('My name is ' + this.name );

}

            //也是静态的

Person.age=12;

//非静态

this.aTest=new Array('aa','bb');

}

//添加静态属性,人都是一张嘴

Person.mouth = 1;

//添加静态方法

Person.cry = function() {

alert('Wa wa wa …');

};

//使用prototype关键字添加非静态属性,每个人的牙可能不一样多

Person.prototype.teeth = 32;

//添加非静态方法

Person.prototype.smile = function() {

alert(this.name+'he he he …');

this.aTest.push('cc');

};

 

Person.prototype.jupm = function() {

alert(this.name+'jump jump …');

var test=this.aTest;

            for(var i in test){

  alert(test[i]);

}

};

//非静态方法必须通过类的实例来访问

var me = new Person('Zhangsan');

me.smile();

me.jupm();

//使用非静态方法、属性

me.show();

alert('I have ' + me.teeth + ' teeth.');

//使用静态方法、属性

Person.cry();

//Person.smile(); 不能调用

alert('I have ' + me.mouth + ' mouth.');//undefined

alert('I have ' + Person.teeth + ' teeth.');//undefined

alert('I have ' + me.age + ' teeth.');//undefined

 

var me2 = new Person('lisi');

me2.jupm();//不受me smile()的影响

me2.smile();

me2.teeth=20;

alert('me2 have ' + me2.teeth + ' teeth.');

alert('me have ' + me.teeth + ' teeth.');

 

 

我认为闭包就是能够读/写函数内部的某些变量的子函数,并将这些变量保存在内存中.

eg:

  function PoliceMan() {

02. //定义初始生命值
03. var lifeEnergy = 100;
04. //中弹减少生命值
05. InBullet = function(){
06. lifeEnergy -= 1;
07. }
08. //显示当前生命值
09. function showLifeEnergy() {
10. alert(lifeEnergy);
11. }
12. return showLifeEnergy;
13. }
14.  
15. //创建一个警察
16. var pm = new PoliceMan();
17. //显示当前生命值
18. pm();
19. //中弹减少生命值
20. InBullet();
   由以上例子我们可以看到警察的生命值变量lifeEnergy会一直驻留在内存当中.如果这种方法使用频繁,那么很容易就把机器的内存消耗完.因此建议能用函数的地方就尽量使用函数,而不要使用闭包
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值