我有一堆 String 和其他 JavaScript 类型的扩展方法,它们现在驻留在全局命名空间中。 组织这些扩展方法的最佳实践是什么?我应该将它们封装在命名空间中吗?如果是,如何实现?谢谢!
最佳答案
Namespace your JavaScript if you need to refer to it elsewhere.
// define your global namespace
var Extensions = Extensions || {};
// add modules to it
Extensions.String = function() {
var myPrivateProperty = 2;
var myPublicProperty = 1;
var myPrivateFunction = function() {
console.log("myPrivateFunction()");
};
var myPublicExtension = function() {
// this extension is being called, now what?
console.log("myPublicExtension()");
};
// this object will be returned, giving access to public vars/methods
return {
myPublicProperty: myPublicProperty,
myPublicExtension : myPublicExtension
};
}();
console.log("Calling myPublicExtension()...");
Extensions.String.myPublicExtension();
Anonymously scope JavaScript if you’re never going to call it elsewhere.
// This will keep your namespace clean
(function() {
// here you can define your modules, functions, etc..
var x = 123;
console.log(x);
// to make something global you can define it like
window.globalVar = 5;
}());
或者您可以使用 prototype 扩展 native javascript 对象像这样:
String.prototype.myExtension = function(p1, p2) {
// here is your function
return this + p1 + p2;
}
这样您就不需要定义命名空间,并且可以直接从您扩展的任何对象调用您的扩展:
var otherString = "mystring".myExtension(" is", " great!");
console.log(otherString);// mystring is cool
你可以用 javascript 中的任何对象来做到这一点
编辑:
原型(prototype)扩展不会污染全局命名空间,因为它们只能通过您扩展的对象进行访问。
如果您有许多扩展,请考虑将它们放入一个文件中,例如extensions.js,然后在需要这些扩展时将其添加到您的页面中。这样extensions.js就可以被浏览器缓存,加载速度会更快
关于javascript - 在 JavaScript 中组织扩展方法的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31573128/