惰性初始化
The Firefox DevTools underlying code, which is written with JavaScript and HTML, is a complex application. Due to the complexity and amount of work going on, the DevTools team has done everything they can to load as little as possible. Furthermore the team has a system of lazily importing and initializing objects when they're needed. I've taken a bit of time to reduce the initializer, let's take a look!
用JavaScript和HTML编写的Firefox DevTools基础代码是一个复杂的应用程序。 由于工作的复杂性和繁重的工作量,DevTools团队已尽其所能来尽可能少地加载。 此外,该团队还具有在需要时懒惰地导入和初始化对象的系统。 我花了一些时间来简化初始化程序,让我们来看一下!
The system relies on taking advantage of Object.defineProperty
's get
function to initialize an object when needed:
系统依赖于利用Object.defineProperty
的get
函数在需要时初始化对象:
// Lazily initializes an object's property until it's used
function lazyGet(hostObj, name, initializer) {
let defined = false;
Object.defineProperty(hostObj, name, {
get: function () {
// If not already defined, define it by executing
// its initializer and setting it as value
if (!defined) {
defined = true;
// Overrides the original property definition
// which is the initializer
Object.defineProperty(hostObj, name, {
configurable: true,
enumerable: true,
value: initializer.apply(hostObj),
writable: true,
});
return hostObj[name];
}
},
configurable: true,
enumerable: true
});
}
With the lazyGet
function, the property you want is only initialized and processing down when its getter is called:
使用lazyGet
函数,仅在调用其getter时初始化并处理所需的属性:
// Don't define window.myProp until someone tries to use it
// Thus, if it's never used, it's never initialized
lazyGet(window, "myProp", () => {
return { message: "Hello!" };
});
// window.myProp is now undefined, since it hasn't been requested yet
// Use it for something, which triggers initialization and returns its value
console.log(window.myProp.message);
// Using it again doesn't initialize again, since it was already created
console.log(window.myProp.message);
// And it can be reassigned later on:
window.myProp = null;
Mozilla's initializer is much more complex as it also acts as a loader, but you get the idea. We always think about lazy loading resources but it's also good to think about initializing properties as they may not be needed! Keep a tiny footprint if you can!
Mozilla的初始化程序要复杂得多,因为它也可以充当加载程序,但是您可以理解。 我们总是考虑延迟加载资源,但最好考虑初始化属性,因为可能不需要它们! 如果可以,请保留很小的空间!
惰性初始化