zoukankan      html  css  js  c++  java
  • javascript面向对象方式,调用属性和方法

    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

  • 相关阅读:
    RDay2-Problem 2 B
    杭电 1862 EXCEL排序(sort+结构体)
    杭电 2803 The MAX(sort)
    杭电 5053 the Sum of Cube(求区间内的立方和)打表法
    杭电 2089 不要62
    杭电 4548 美素数(素数打表)
    杭电2098 分拆素数和
    杭电1722 Cake (分蛋糕)
    素数判定 (素数打表)
    最小公倍数
  • 原文地址:https://www.cnblogs.com/hujiapeng/p/4895360.html
Copyright © 2011-2022 走看看