在JavaScript中创建Namespace / Class类型结构的最优雅方式 [英] Most elegant way to create a Namespace/Class type structure in JavaScript

查看:82
本文介绍了在JavaScript中创建Namespace / Class类型结构的最优雅方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图找到一种方法,它将为我提供最优雅的方式将我的代码包装在命名空间 / 单位喜欢对象。例如Google Maps API的 var a = Google.Maps.Foo(); ,我认为这看起来很干净。

I am trying to settle on a method that will provide me the most elegant way of wrapping my code in Namespace/Unit like objects. For example Google Maps API's var a = Google.Maps.Foo();, which I think seems quite clean.

我希望附上(如果这是正确的术语) jQuery 无冲突 $ 也签名。

I'd like it to enclose (if that is the right term) the jQuery No Conflict $ sign as well.

到目前为止我很喜欢:

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

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

Can anyone expand on this, point out potential problems, or just offer a better methodology in general?

推荐答案

检查这个 JavaScript模块模式
学习JavaScript设计模式

模块示例:

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

这篇关于在JavaScript中创建Namespace / Class类型结构的最优雅方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆