4

js-惰性函数

 1 year ago
source link: https://www.fly63.com/article/detial/12389
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

我们现在需要写一个 foo 函数,这个函数返回首次调用时的 Date 对象,注意是首次。

使用场景:

当我们每次都需要进行条件判断,其实只需要判断一次,接下来的使用方式都不会发生改变的时候,想想是否可以考虑使用惰性函数。

惰性函数:

顾名思义,有点懒惰,懒到事件只处理一次,当然不是值整个函数只处理一次。而是里面的某一行或者多行只执行一次。正常情况下,一个函数内部,所有的该执行的东西,无论是定义变量,还是新建对象,亦或者做判断,还是运算,定义定时器等等,都是依照顺序来执行,无论这个函数执行调用多少次,都依旧是如此;

简单理解下,惰性函数的本质就是函数重写,所谓惰性载入,指函数执行的分支只会发生一次。

为了不影响全局变量,我们用闭包简单来做:

function foo() {
if (foo.t) return foo.t;
foo.t = new Date();
return foo.t;
}

但是每次执行都需要进行一次判断,为了解决每次都需要判断的情况,使用惰性函数

var foo = function() {
var t = new Date();
foo = function() {
return t;
}
console.log(foo, 'foo');
console.log(foo(), 'foo()');
return foo()
}
console.log(foo());
setTimeout( () => {
console.log(foo());
}, 3000)

最后发现两次打印一摸一样,因为第一次执行立即执行函数的时候,没有跳过var t = new Date();这一步,并且把一个新的函数返回给了foo,第二次执行的时候,foo函数只会执行:立即执行函数中的那个新的函数,也就跳过了var t = new Date();直接使用第一次调用的t的值。

来自:https://www.cnblogs.com/tdcqcrtd/archive/2023/02/27/17158290.html

链接: https://www.fly63.com/article/detial/12389


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK