JavaScript面向对象

声明对象一

function 对象名称() 
{
}            
// 此种方法相当于定义公共属性和方法
对象名称.prototype = 
{
    属性一 : 属性值,
    
    属性二 : 属性值,
    
    方法一 : function(参数列表) 
    {
        方法体;
    },
    
    方法二 : function(参数列表) 
    {
        方法体;
    }
}

Code Example

// Rect 对象        
function Rect()
{ // 相当于构造函数
}
// 声明公共变量及方法
Rect.prototype = 
{
    left:0,
    top:0,
    right:0,
    bottom:0,
    getCenterX:function()
    {
        return (left + right) / 2;
    },
    getCenterY:function()
    {
        return (top + bottom) / 2;
    }
}

 

声明对象二

function 对象名称()
{
    // 私有属性
    var 属性一;
    var 属性二;
    
    // 公共属性
    this.属性三;
    this.属性四;
    
    // 公共方法
    this.方法一 = function(参数列表)
    {
        方法体;
    }
    this.方法二 = function(参数列表)
    {
        方法体;
    }
}

Code Example

function Rect()
{
    var left;
    var top;
    var right;
    var bottom;
    this.getCenterX = function()
    {
        return (left + right) / 2;
    }
    this.getCenterY = function()
    {
        return (top + bottom) / 2;
    }        
}

 

静态变量方法

对象名称.静态变量 = 值
对象名称.静态方法 = function()
{
    静态方法体
}

Code Example

// 声明静态变量
Rect.STATIC_VARIABLE = "test"

// 声明静态方法
Rect.area = function(width, height)
{
    return width * height;
}

 

posted on 2014-01-04 19:29  麥籽  阅读(202)  评论(0编辑  收藏  举报