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

  • 相关阅读:
    美团DSP
    pid稳态控制
    Tensorflow的gRPC编程(一)
    信息增益,信息增益率
    tensorflow dnn 参考
    java tfserving grpc 通信调用代码解析 【重点参考】
    Saltstack module dnsmasq 详解
    Saltstack module django 详解
    Saltstack module disk 详解
    Saltstack module dig 详解
  • 原文地址:https://www.cnblogs.com/hujiapeng/p/4895360.html
Copyright © 2011-2022 走看看