JavaScript 定义Class的方式

来源:互联网 发布:安卓client软件 编辑:程序博客网 时间:2024/06/06 09:37

  JavaScript 作为一种简单灵活的语言,随着互联网,智能客户端的发展,变得越来越举重若轻。虽然JS不是一种以类为基础的面向对象的程序设计语言,但是它在模拟像Java和C++这样以类为基础的语言时做得相当出色。JavaScript定义Class的方式,有下面几种写法。

1. 直接定义函数

function userModel(element, flag){   /*---Public Variables ---- */    this.ctb_timeout = 20;    this.ctb_charCount = 10;    this.ctb_element = element;    this.ctb_flag = flag;    /*---- Static Variables*/    userModel.mouse_down;    userModel.mouse_up;       /* ---- Private Variables ---- */   var stop_seconds = 10;   var request_url = "";   /*---Self reference ---- */   var ctb_self = this;   /*---Methods ---- */   function ctb_get()   {..}      function ctb_remove(arg1, arg2)   {...}    return this;}

2. 匿名函数

var UserModel = function(element, flag){    this.timeOut = 20;    this.charCount = 10;    this.element = element;    this.flag = falg;       this.get = function() {...};    this.remove = function(arg1, arg2) {...};    }

3. 使用prototype

function UserModel(element, flag){  this.element = element;  this.flag = flag;}/*----Instance function -------*/UserModel.prototype.get = function() {...};UserModel.prototype.remove = function() {...};/*---- Static function (Class method)*/UserModel.Compare = function(a, b) {return a.flag > b.flag; };UserModel.Clone = function(a) {return new UserModel(a.flag, a.element);};/*---- Static variable (Class variable)*/UserModel.TimeOut = 20;


4. 对象直接量

var userModel = userModel || {};userModel.get = function() {...};userModel.remove = function(arg1, arg2) {...};

比较而言,本人更加喜欢第2种的定义方法,简洁优雅。注意第4种方式,可以用来组织JavaScript代码,根NameSpace是userModel。