How to “properly” create a custom object in JavaScript?

后端 未结 15 2005
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 08:07

I wonder about what the best way is to create an JavaScript object that has properties and methods.

I have seen examples where the person used var self = this<

15条回答
  •  梦谈多话
    2020-11-21 08:38

    Another way would be http://jsfiddle.net/nnUY4/ (i dont know if this kind of handling object creation and revealing functions follow any specific pattern)

    // Build-Reveal
    
    var person={
    create:function(_name){ // 'constructor'
                            //  prevents direct instantiation 
                            //  but no inheritance
        return (function() {
    
            var name=_name||"defaultname";  // private variable
    
            // [some private functions]
    
            function getName(){
                return name;
            }
    
            function setName(_name){
                name=_name;
            }
    
            return {    // revealed functions
                getName:getName,    
                setName:setName
            }
        })();
       }
      }
    
      // … no (instantiated) person so far …
    
      var p=person.create(); // name will be set to 'defaultname'
      p.setName("adam");        // and overwritten
      var p2=person.create("eva"); // or provide 'constructor parameters'
      alert(p.getName()+":"+p2.getName()); // alerts "adam:eva"
    

提交回复
热议问题