幾種常用的JS類定義方法


// 方法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;
}

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());

alert(obj1);
alert(obj2);
alert(obj3);
alert(obj4);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM