`

js 对象

    博客分类:
  • 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会一直驻留在内存当中.如果这种方法使用频繁,那么很容易就把机器的内存消耗完.因此建议能用函数的地方就尽量使用函数,而不要使用闭包
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics