【JavaScript】经过闭包建立具备私有属性的实例对象

静态私有变量

(function(){
    //私有属性
    var name = '';
    Person = function(value) {
        name = value;
    };
    //特权方法
    Person.prototype.getName = function() {
        return name;
    };
    Person.prototype.setName = function(value) {
        name = value;
    };
})();
var person = new Person('hiyohoo');
console.log(person.getName()); //hiyohoo
person.setName('xujian');
console.log(person.getName()); //xujian

模块模式

模块模式是为单例建立私有变量和特权方法。单例是只有一个实例的对象。这种模式经常使用于对单例进行某种初始化,同时又须要维护其私有变量。segmentfault

var student = function() {
    //私有变量和函数
    var students = new Array();
    //初始化
    students.push(new Person());
    //公共
    return {
        getStudentCount: function() {
            return students.length;
        },
        registerStudent: function(person) {
            if (person instanceof Person) {
                students.push(person);
            }
        }
    };
}();

加强的模块模式

这种模式专用于单例必须是某种类型的实例,同时还必须添加某些属性和方法对其增强的状况。在下面的例子中,student的值是匿名函数返回的stu,也就是Person的一个实例,这个实例有两个公共的方法,用于访问实例属性。函数

var student = function() {
    //私有变量和函数
    var students = new Array();
    //初始化
    students.push(new Person());
    //建立student的一个局部副本
    var stu = new Person;
    //公共接口
    stu.getStudentCount = function() {
        return students.length;
    };
    stu.registerStudent = function(preson) {
        if (person instanceof Person) {
            students.push(person);
        }
    };
    //返回这个副本
    return stu;
}();

转载请注明出处:http://www.javashuo.com/article/p-gehuvfjp-mq.htmlprototype

文章不按期更新完善,若是能对你有一点点启发,我将不胜荣幸。code

相关文章
相关标签/搜索