functions-once1
by shan10213223
JavaScript
var _ = {};
// _.once(func)
// Creates a version of the function that can only be called one time.
// Repeated calls to the modified function will have no effect,
// returning the value from the original call. Useful for initialization functions,
// instead of having to set a boolean flag and then check it later.
_.once = function (func) {
let called = false;
let result;
return function () {
if (!called) {
result = func.apply(this, arguments);
called = true;
}
return result;
}
};
// ref
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
// tests
var initialize = _.once(createApplication);
initialize();
initialize();
// Application is only created once.