您的位置:首页 > Web前端 > JavaScript

javascript面向对象方式,调用属性和方法

2015-10-20 17:19 761 查看
1、定义一个Person类,其中的属性和方法如果想对外开放,需要使用this,如:

var Person=function(name,age,sex){

  var psex='Boy';

  if(sex){

    psex=sex;

  }

  this.name=name;

  this.age=age;

  this.speak=function(){

    console.log('My name is '+this.name+';I am '+this.age+' years old'+';I am a '+psex);

  }

}

2、创建Person对象调用内部公开属性和方法,如果调用了非公开的属性,结果显示undefined,如果调用非公开的方法,会报错not a function。

案例:var p=new Person('Tom',23);p.speak();//My name is Tom;I am 23 years old;I am a Boy

   var pp=new Person('Lily',21,'Girl');pp.speak();//My name is Lily;I am 21 years old;I am a Girl

每次new都会独立开辟一个空间给对象

3、扩展Person类的对象属性和实例方法(使用类的prototype扩展)

  扩展对象属性:Person.prototype.hobby='play basketball';//设置默认属性值

         p.hobby;//play basketball

         pp.hobby;//play basketball

         pp.hobby='play badminton';//重新设置pp对象的hobby属性值

         p.hobby;//play basketball

         pp.hobby;//play badminton

  扩展对象方法:Person.prototype.run=function(){console.log('I am running');}

         p.run();//I am running

         pp.run();//I am running

如果用创建出的对象p或pp来扩展属性和方法,则只能由该对象调用自己的属性和方法。比如p.walk=function(){console.log('walk')};p.walk();//walk;如果使用pp调用报错“pp.walk is not a function”。

4、扩展Person类的静态属性和静态方法(直接使用类名扩展)

   扩展静态属性:Person.test='test static attribute';Person.test;//test static attribute如果用对象调用该test属性,则输出undefined

   扩展静态方法:Person.eat=function(){console.log('I am eating an apple')};Person.eat();//I am eating an apple如果用对象调用报错 is not a function
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: