js 定义类

来源:互联网 发布:清新博客程序源码 编辑:程序博客网 时间:2024/04/28 12:39

1、方法一:对象直接量

var obj1 = {    v1 : "",    get_v1 : function() {        return this.v1;    },    set_v1 : function(v) {        this.v1 = v;    }};

2、方法二:定义函数对象

var Obj = function() {    var v1 = "";    this.get_v1 = function() {        return this.v1;    };    this.set_v1 = function(v) {        this.v1 = v;    }};

3、方法三:原型继承

var Obj3 = new Function();Obj3.prototype = {    v1 : "",    get_v1 : function() {        return this.v1;    },    set_v1 : function(v) {        this.v1 = v;    }};

4、方法四:工厂模式

function loadObj() {    var tmp = new Object();    tmp.v1 = "";    tmp.get_v1 = function() {        return tmp.v1;    };    tmp.set_v1 = function(v) {        tmp.v1 = v;    };    return tmp;}

5、调用

obj1.set_v1('hello1');alert(obj1.get_v1());var obj2 = new Obj();obj2.set_v1('hello2');alert(obj2.get_v1());var obj3 = new Obj();obj3.set_v1('hello3');alert(obj3.get_v1());var obj4 = loadObj();obj4.set_v1('hello4');alert(obj4.get_v1());


原文地址:http://www.cnblogs.com/xusir/archive/2013/01/17/2863882.html



0 0
原创粉丝点击