码迷,mamicode.com
首页 > Web开发 > 详细

js面向对象浅析

时间:2016-01-21 01:47:41      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

 

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里new出生的对象不能使用类的成员变量,而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_widht * s_height;

}

js面向对象浅析

标签:

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

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