How to create an object with private members using Object.create() instead of new

前端 未结 2 1693
臣服心动
臣服心动 2020-12-10 16:45

EDIT: I figured it out from Bergi\'s answer in the end.

Thanks Bergi.

pubPrivExample = (function () {
    return {
        init : function () {
             


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 17:00

    I think this is a clear way to achieve your requirements:

    var personFactory = function(id, name, age){
        var _id = id;
        var _name = name;
        var _age = age;
    
        var personPrototype = {
            getId: function(){
                return _id;
            },
            setId: function(id){
                _id = id;
            },
            getName: function(){
                return _name;
            },
            setName: function(name){
                _name = name;
            },
            getAge: function(){
                return _age; 
            },
            setAge: function(age){
                _age = age;
            },
            work: function(){
                document.write(this.toString());
            },
            toString: function(){
                return "Id: " + _id + " - Name: " + _name + " - Age: " + _age;
            }
        };
    
        return Object.create(personPrototype);
    };
    

    Usage:

    var renato = personFactory(1, "Renato Gama", 25);
    console.log(renato.getName()); //logs "Renato Gama"
    renato.setName("Renato Mendonça da Gama");
    console.log(renato.getName()); //logs "Renato Mendonça da Gama"
    

    If I am not wrong this is one the MODULE PATTERN usages. Refer to this post for a nicer explanation. This is also a good post about the subject.

提交回复
热议问题