js面向对象浅析

1.类结构剖析

function fn(){
      var variable = "";  //特定属性
      function method(){};   //特定方法
      this.propertyName = value;   //公共属性 
      this.method = function(){};//公共方法
}

ps: 特定属性和特定方法是用于函数fn内部使用的,不可被外界访问。而公共属性和公共方法是在函数被new后所创建的对象应该拥有的属性和方法,因此说可以被外界所访问。若没有new关键字,则会被认为是普通函数调用,this指向会是window对象。

     此外,还可以直接这样写:

     fn.propertyName 或 fn.method = function(){};

     就好比java中类的静态变量,在js里实例不能使用类的成员变量,这是因为实例没有继承到类的成员,继承是靠原型链prototype来实现的。java中类和对象都可以使用。

2.矩形类

function Rect(width.height){
   this.r_width= width;
   this.r_height= height;
   this.desc = function(){
       return '我是一个矩形哦';
   };
};

//扩展矩形计算面积方法
Rect.prototype.getArea = function(){
   return this.r_width * this.r_height;
};

//打印结果函数
Rect.prototype.toString = function(){
alert("这个矩形的面积是:"+this.getArea()+",宽度是:"+this.r_width+",高度是:"+this.r_height);
};

3.平行四边形类

function Square(value){
    this.s_width = value;
    this.s_height = value;
};

Square.prototype = Rect.prototype; //将Rect的prototype对象赋给Square,拿不到Rect的特有属性和方法,并且会覆盖Square中原有扩展的属性或方法。若不想被覆盖,可在后面继续加Square.prototype.method= function{};

Square.prototype = new Rect();//这种写法会拿到Rect特有的属性和方法,还包括Rect中原型链的东西。同时也需要注意Square.prototype容易被覆盖的问题,一般写在后面扩展。

例如:
Square.prototype.say = function(){
     return "我是一个平行四边形";
};

同时也可对继承过来的属性和方法进行覆盖

Square.prototype.getArea  = function(){
    return this.s_width * s_height;
}

  

原文地址:https://www.cnblogs.com/dzyBlog/p/5147003.html