Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

认识 Lazy Function Definition #35

Open
YIXUNFE opened this issue Nov 20, 2015 · 1 comment
Open

认识 Lazy Function Definition #35

YIXUNFE opened this issue Nov 20, 2015 · 1 comment

Comments

@YIXUNFE
Copy link
Owner

YIXUNFE commented Nov 20, 2015

认识 Lazy Function Definition

记得有一期的 blog 我们讲了通过 code review 、变量命名技巧等尽可能的去除代码中的 if else。今天我们再来认识一个方法,它可以让我们的程序在运行过程中自动“瘦身”,这种方法一般称之为 Lazy Function Definition。


## 定义函数也能懒?

我们接触过很多“懒”的场景,常见的比如图片懒加载,数据懒加载,那么函数也可能“懒”吗?

通常我们在定义一个函数后,即使没执行,JS 引擎也已经将函数解析好只等待程序调用了。但是一个函数是可以在其内部定义子函数的,而内部定义的子函数只有在这个父函数被执行时才会被引擎解析并放入内存。

var son
function parent () {
  son = function () {
    console.log('son')
  }
}

console.log(son) // undefined

parent()

console.log(son) // function

parent 函数运行之后,son 变量被赋值成了一个匿名函数,而在 parent 运行之前它还是 undefined。这里的 son 函数就可以被称为是一个“懒”函数。

在实际工作中,我们有时是可以利用懒函数的特性的提升 Javascript 的运行效率的。


## 为了效率

比如有一个方法,在 PC 或者 Mobile 中的处理方式不同。

var fn = function () {
  if (isPC) {
    alert('PC')
  } else {
    alert('mobile')
  }
}

每一次执行 fn,都需要执行一次判断是否在 PC 中,但其实一般情况下一个网页不可能在加载完成后从 PC 变化到移动端或者从移动端变化到 PC。所以重复的执行这个判断并没有必要。

那该怎么办?

重新定义 fn 吧

var fn = function () {
  if (isPC) {
    alert('PC')
    fn = function () {alert('PC')}
  } else {
    alert('mobile')
    fn = function () {alert('mobile')}
  }
}

fn 方法第一次执行后,就判断出了是在 PC 还是移动端执行代码,处理完方法本来的内容后,顺带重新定义了一个匿名函数给 fn,这样以后再调用 fn 时就不会再执行判断了。


## 适用场景

Lazy function 的适用场景还是比较常见的,当遇到一次运行过程中确定后就不会改变的条件时,就可以用该方法简化已确定条件相关的判断。

比如在做一个简单的 slider 的时候,slider 组件的滑动方向仅水平或垂直中的一种,我们就可以在滑动方向上简化组件的滑动方法。

move: (function () {
  return function (dist) {
    if (dir === 'h') {
      this.dom.style.left = dist + 'px'
      this.move = function (dist) {
        this.dom.style.left = dist + 'px'
      }
    } else {
      this.dom.style.top = dist + 'px'
      this.move = function (dist) {
        this.dom.style.top = dist + 'px'
      }
    }
  }
}())

希望对大家有用 :)


## Thanks
@jincdream
Copy link

具体运用实例?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants