为 window.object 实现私有函数
implementing private functions for a window.object
我正在为将在几个不同的应用程序中使用的 API 创建一个包装器。
我正在使用全局对象并将各种函数作为不同的键放入该对象中。所以我会有:
window.globalContainer = {
APIEndpoint1: function(){
make API call and resolve result
},
APIEndpoint2: function(){},
...
}
API 调用的所有内容都直接在函数中。也就是说,您可以从控制台转到 window.globalContainer.APIEndpoint1 并查看整个函数。
对于跨多个应用程序使用并充当辅助库的东西,这通常是不好的做法吗?或者这是可以接受的吗?我查看了控制台中的 jQuery,它似乎做了很多相同的事情。如果不赞成,我如何在全局对象中实现私有函数?
您可以使用 IIFE 实现私有 functions/properties。
window.globalContainer = function () {
//what ever you define here is not accessible outside. Only the API in
//the returned object is accessible outside
function private1() {
make API call and resolve result
}
return {
APIEndpoint1: function(){
private1();
},
APIEndpoint2: function(){},
...
}
}();
匿名闭包是一个不错的起点:
(function (global) {
var foo = global.foo || {};
//accessible
foo.publicVar = 5;
foo.publicFcn = function (a, b) {
privateFcn(a, b);
...
};
//not accessible
var privateVar = 5;
function privateFcn(a, b) {
...
}
global.foo = foo;
})(window)
有了这些,您可以非常直观地构建一个库,并且不会污染命名空间。
您明确说明了您希望哪些变量和函数可访问。
我正在为将在几个不同的应用程序中使用的 API 创建一个包装器。
我正在使用全局对象并将各种函数作为不同的键放入该对象中。所以我会有:
window.globalContainer = {
APIEndpoint1: function(){
make API call and resolve result
},
APIEndpoint2: function(){},
...
}
API 调用的所有内容都直接在函数中。也就是说,您可以从控制台转到 window.globalContainer.APIEndpoint1 并查看整个函数。
对于跨多个应用程序使用并充当辅助库的东西,这通常是不好的做法吗?或者这是可以接受的吗?我查看了控制台中的 jQuery,它似乎做了很多相同的事情。如果不赞成,我如何在全局对象中实现私有函数?
您可以使用 IIFE 实现私有 functions/properties。
window.globalContainer = function () {
//what ever you define here is not accessible outside. Only the API in
//the returned object is accessible outside
function private1() {
make API call and resolve result
}
return {
APIEndpoint1: function(){
private1();
},
APIEndpoint2: function(){},
...
}
}();
匿名闭包是一个不错的起点:
(function (global) {
var foo = global.foo || {};
//accessible
foo.publicVar = 5;
foo.publicFcn = function (a, b) {
privateFcn(a, b);
...
};
//not accessible
var privateVar = 5;
function privateFcn(a, b) {
...
}
global.foo = foo;
})(window)
有了这些,您可以非常直观地构建一个库,并且不会污染命名空间。
您明确说明了您希望哪些变量和函数可访问。