JavaScript--构造函数

2017-03-16  本文已影响0人  岩蔷薇
<script>
      function Car(type,number){
      this.type = type;    //公有属性
      this.number = number;

      var city = "北京";           //私有属性
      var getNumber = function(){
          return number;
      };
      var getType = function(){
          return type;
    };

      //能够访问私有变量和函数的方法 -----特权方法
    this.getDescription = function(){             //this指向的是构造函数创建的实例对象
    console.log(getNumber() + getType() + city);
    }
 }
  var car = new Car("汽车","123456");
  car.getDescription();
</script>

私有属性:定义在构造函数内部的变量和函数;不能在构造函数之外的访问变量和函数。
公有属性:能够被构造函数创建的所有对象访问;
特权法:通过this指针在构造函数内部访问私有变量和函数的方法。

上一篇下一篇

猜你喜欢

热点阅读