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 扩展原生 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 中的任何对象做到这一点
编辑:
原型扩展不会污染全局命名空间,因为它们只能通过您扩展的对象访问。
如果您有许多扩展程序,请考虑将它们放入 extensions.js 之类的文件中,然后在您需要这些扩展程序时将其添加到您的页面中。这样 extensions.js 可以被浏览器缓存,加载速度更快