码迷,mamicode.com
首页 > 编程语言 > 详细

Javascript进阶(5)---编写类

时间:2016-10-06 22:20:05      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

Javascript类的编写

  • 在内部定义变量和方法
  1. 凡是定义共公共属性与公共方法都要使用this声明
  2. 在内部的 var 声明,或者直接不写var(隐式声明)的都为死哟属性与私有方法
  3. 类的实例只能够访问公共属性与公共方法
      function Pet(_name,_age,_price){
        this.name=_name;
        var age=_age;    //私有属性
        var price=_price;//私有属性
        this.setAge = function(intAge) {
          age = intAge;
       }
        /*定义私有属性Age的对外公开访问方法*/
         this.getAge = function() {
           return age;
          }
       }
  • 使用prototype,在原型链上定义方法与属性
  1. 使用prototype定义的属性与方法都是共有的
  2. 写法 ①在类的内部给出共有的构造方法 或者 ② 直接将类定义为空,然后直接将类的prototype写成JS对象的形式

  写法一:

/*使用写法①定义一个Pet类*/
function Pet(_name, _age, _price, _color)
{
    this.init(_name, _age, _price, _color);
}

Pet.prototype.name;
Pet.prototype.age;
Pet.prototype.price;
Pet.prototype.color;
Pet.prototype.init = function (_name, _age, _price, _color) 
{
    if (_name != undefined && _age != undefined && _price != undefined && _color != undefined)
    {
        this.name = _name;
        this.age = _age;
        this.price = _price;
        this.color = _color;
        document.writeln("this.name=" + this.name + ",this.age=" + this.age + ",this.price=" + this.price + ",this.color=" + this.color);
    }
}

 

  写法二:

function Person2() { } 
/*在类的prototype上以JS对象的形式构造一个类*/ Person2.prototype = { name : "", //public属性 age : 0, weight : 0, height : 0, /*public方法*/ init : function (_name, _age, _weight, _height) { this.name = _name; this.age = _age; this.weight = _weight; this.height = _height; document.writeln("this.name=" + this.name + ",this.age=" + this.age + ",this.weight=" + this.weight + ",this.height=" + this.height); }, /*public方法*/ show : function () { document.writeln("show method"); } };

  


 

利用上面归纳的特点,我们可以总结出一套高效可行的编写方法

  • 使用构造函数的方式来定义public属性,private属性
  • 用原型链prototype的方式来定义类的方法(public方法),然后利用这些方法去访问public的和private的属性
/*定义一个Person类*/
function Person(_name, _age, _price)
{
    this.name = _name;
    var age = _age;
    //私有属性,只能在类内部使用
    var price = _price;
    //私有属性,只能在类内部使用
    function privateFn()
    {
        console.log("我是Pet类的私有属性age,只能在Pet类内部使用,初始化后age=" + age);
        console.log("我是Pet类的私有函数privateFn,只能在Pet类内部使用");
    }
    var privateFn2 = function ()
    {
        console.log("我是Pet类的私有属性price,只能在Pet类内部使用,初始化后price=" + price);
        console.log("我是Pet类的私有函数privateFn2,只能在Pet类内部使用");
    }
    privateFn();
    //在Pet类内部调用私有方法
    privateFn2();
    //在Pet类内部调用私有方法
}
Pet.prototype = 
{
    setName : function (_name)
    {
        this.name = _name;
    },
    getName : function ()
    {
        return this.name;
    },
    show : function ()
    {
        console.log("公开方法show");
    }
}; 

参考资料:http://www.cnblogs.com/xdp-gacl/p/3700840.html

  

Javascript进阶(5)---编写类

标签:

原文地址:http://www.cnblogs.com/HXW-from-DJTU/p/5934970.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!