在 JavaScript 中创建命名空间/类类型结构的最优雅方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15659283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Most elegant way to create a Namespace/Class type structure in JavaScript
提问by Gga
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.
我正在尝试确定一种方法,该方法将为我提供将代码包装在Namespace
/Unit
类对象中的最优雅方式。例如 Google Maps API 的var a = Google.Maps.Foo();
,我认为它看起来很干净。
I'd like it to enclose(if that is the right term) the jQuery
No Conflict
$
sign as well.
我希望它也附上(如果这是正确的术语)jQuery
No Conflict
$
标志。
So far I am liking:
到目前为止,我喜欢:
// 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?
任何人都可以对此进行扩展,指出潜在的问题,或者只是提供一种更好的方法论吗?
回答by kayz1
Check this JavaScript Module Patternand this Learning JavaScript Design Patterns
检查这个JavaScript 模块模式和这个学习 JavaScript 设计模式
Module example:
模块示例:
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();
Class example:
类示例:
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();