这两个功能来自我所采取的课程(https://www.udacity.com/course/front-end-web-developer-nanodegree--nd001)。代码和评论来自课程提供者:
/* This is the publicly accessible image loading function. It accepts
* an array of strings pointing to image files or a string for a single
* image. It will then call our private image loading function accordingly.
*/
function load(urlOrArr) {
if(urlOrArr instanceof Array) {
/* If the developer passed in an array of images
* loop through each value and call our image
* loader on that image file
*/
urlOrArr.forEach(function(url) {
_load(url);
});
} else {
/* The developer did not pass an array to this function,
* assume the value is a string and call our image loader
* directly.
*/
_load(urlOrArr);
}
}
/* This is our private image loader function, it is
* called by the public image loader function.
*/
function _load(url) {
if(resourceCache[url]) {
/* If this URL has been previously loaded it will exist within
* our resourceCache array. Just return that image rather
* re-loading the image.
*/
return resourceCache[url];
} else {
/* This URL has not been previously loaded and is not present
* within our cache; we'll need to load this image.
*/
var img = new Image();
img.onload = function() {
/* Once our image has properly loaded, add it to our cache
* so that we can simply return this image if the developer
* attempts to load this file in the future.
*/
resourceCache[url] = img;
/* Once the image is actually loaded and properly cached,
* call all of the onReady() callbacks we have defined.
*/
if(isReady()) {
readyCallbacks.forEach(function(func) { func(); });
}
};
/* Set the initial cache value to false, this will change when
* the image's onload event handler is called. Finally, point
* the image's src attribute to the passed in URL.
*/
resourceCache[url] = false;
img.src = url;
}
}
为什么load()
"可公开访问"虽然_load()
是"私有"?公共/私人在这种背景下意味着什么?
如果您需要,完整档案位于https://github.com/YolkFolkDizzy/frontend-nanodegree-arcade-game/blob/master/js/resources.js
答案 0 :(得分:3)
它是私有的,因为无法直接调用...请参阅第105行:
window.Resources = {
load: load,
get: get,
onReady: onReady,
isReady: isReady
};
由于方法在范围内声明,因此在其他任何地方都无法使用。
你可以看到代码写在里面:
(function() {
...
})()
它强制将任何函数声明或变量声明附加到当前作用域。如果没有这个,变量将附加到最近的当前对象通常窗口。因此永远不会导出_load
,并且调用它的唯一方法是调用window
对象中Resource
上导出的方法之一。
在Javascript中,通常私有属性隐藏在仅对该范围内创建的函数可用的范围内。