一、前言
实现函数只执行一次的核心思想非常的简单:「通过记录是否被执行的状态,来决定函数是否需要被调用」。
function start() {
console.log('invoke start function');
}
// 记录状态
let invoked = false;
if (!invoked) {
invoked = ture;
start();
}
但是直接使用上述实现方式会存在一个巨大的缺点:「产生大量的模板代码」。
接下来,一起探寻如何将其一步一步地优化处理。
二、闭包
利用闭包「延长变量生命周期」的特性将状态与目标函数绑定在一起:
function once(fn) {
let called = false;
return function _once() {
if (called) {
return _once.value;
}
called = true;
_once.value = fn.apply(this, arguments);
}
}
上述代码利用闭包中声明的 called 变量保存当前函数是否执行的状态,并且记录函数第一次执行的返回值,供后续使用。
使用方式如下:
let index = 0;
const increment = () => index++;
const onceIncrement = once(increment);
onceIncrement();
onceIncrement();
onceIncrement();
console.log(index); // 1
三、元编程
利用 ES6 的元编程 Reflect API 将其定义为函数的行为:
Reflect.defineProperty(Function.prototype, 'once', {
value () {
return once(this);
},
configurable: true,
})
然后就可以这样使用:
let index = 0;
const increment = () => index++;
const onceIncrement = increment.once();
onceIncrement();
onceIncrement();
onceIncrement();
console.log(index); // 1
四、自身属性丢失
虽然把函数只执行一次的功能封装成了通用的工具函数,但是还存在一些问题。「由于闭包是返回一个新的函数,所以会导致原函数本身携带的一些属性会丢失」:
const increment = () => index++;
increment._flag_ = true;
const onceIncrement = increment.once();
console.log(onceIncrement._flag_); // undefined
那么就需要在返回 _once 函数时,将原函数的属性复制过来。
而 JavaScript 获取一个对象的属性集合时,有如下几种方法:
Object.keys:获取自身可枚举的属性集合
Object.getOwnPropertyNames:获取自身包含不可枚举的属性集合,但是不包含 Symbol 属性
Object.getOwnPropertySymbols:获取自身所有的 Symbol 属性
Reflect.ownKeys:获取自身所有的属性
const once = fn => {
let called = false;
const _once = function () {
if (called) {
return _once.value;
}
called = true;
_once.value = fn.apply(this, arguments);
}
for (const property of Reflect.ownKeys(fn)) {
copyProperty(to, from, property)
}
return _once;
}
拿到对象自身所有的属性集合时,不能简单地通过等号去赋值,这里主要考虑到:
函数本身一些特有的属性,不应该被覆盖
保持原有属性的属性描述符
function copyProperty(to, from, property) {
// 一些特殊的属性不应复制
if (property === 'length' || property === 'prototype' || property === 'arguments' || property === 'caller') {
return;
}
const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
if (!canCopyProperty(toDescriptor, fromDescriptor)) {
return;
}
Object.defineProperty(to, property, fromDescriptor);
}
function canCopyProperty(toDescriptor, fromDescriptor) {
if (toDescriptor === undefined) {
return true;
}
if (toDescriptor.configurable) {
return true;
}
if (toDescriptor.writable === fromDescriptor.writable &&
toDescriptor.enumerable === fromDescriptor.enumerable &&
toDescriptor.configurable === fromDescriptor.configurable &&
(toDescriptor.writable || toDescriptor.value === fromDescriptor.value)) {
return true;
}
return false;
}
五、原型链上的属性
当对象上不存在某个属性时,JavaScript 的查找机制会顺着其原型链一步一步向上找,所以还需要考虑原型链的正确设置:
const changePrototype = (to, from) => {
const fromPrototype = Object.getPrototypeOf(from);
if (fromPrototype === Object.getPrototypeOf(to)) {
return;
}
Object.setPrototypeOf(to, fromPrototype);
};
六、写在最后
以上就是本文的全部内容,希望能够给你带来帮助,欢迎「关注」、「点赞」、「转发」。
参考资料:
https://github.com/isaacs/once
https://github.com/sindresorhus/onetime