在JavaScript中创建Namespace / Class类型结构的最优雅方式

时间:2013-03-27 12:52:17

标签: javascript jquery design-patterns module closures

我正在努力解决一种方法,它将为我提供在Namespace / Unit类似对象中包装代码的最优雅方式。例如Google Maps API的var a = Google.Maps.Foo();,我觉得它看起来很干净。

我希望附上(如果这是正确的术语)jQuery No Conflict $符号。

到目前为止,我很喜欢:

// Top level container for sub objects
var myApp = myApp || {}; 

// An object to be held in myApp     
(function( skillet, $, undefined ) {

    //Private Property
    var isHot = true;

    //Public Property
    skillet.ingredient = "Bacon Strips";

    //Public Method
    skillet.fry = function() {
        var oliveOil;

        addItem( "\t\n Butter \n\t" );
        addItem( oliveOil );
        console.log( "Frying " + skillet.ingredient );

        return "Fried!";
    };

    //Private Method
    function addItem( item ) {
        if ( item !== undefined ) {
            console.log( "Adding " + $.trim(item) );
        }
    }   

}( window.myApp.skillet = window.myApp.skillet || {}, jQuery ));

任何人都可以对此进行扩展,指出潜在问题,或者只提供更好的方法吗?

1 个答案:

答案 0 :(得分:11)

检查JavaScript Module Pattern 这个Learning JavaScript Design Patterns

模块示例:

var MyModule = (function($){
  var MY_CONSTANT = 123;

  var _myPrivateVariable = 'TEST MEH';
  var _$myPrivateJqueryObject = $('div.content');

  var _myPrivateMethod = function(){
    alert('I am private!');
  };

  var myPublicMethod = function(){
    console.log('Public much?');
  }

  return {
      myPublicMethod : myPublicMethod 
  };

})(jQuery);

MyModule.myPublicMethod();

类示例:

function Person(name, age){
   this.name = name || '';
   this.age = age || -1;
}

Person.prototype.greet= function(){
   console.log('Hi! My name is' + this.name + '. Old ' + this.age + ' I am.');
}

var person = new Person("John", 12);
person.greet();