This is called closure.

每次提到closure首先想到的都是「Friends」里Rachel喝高了给Ross留语音的这个场景.. 🙂

closure

 

好了当然我说的不是这个。

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure ‘remembers’ the environment in which it was created.

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains:

  1. it has access to its own scope (variables defined between its curly brackets)
  2. it has access to the outer function’s variables
  3. it has access to the global variables.

The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.

Continue reading “This is called closure.”

More about DOM

上次回来以后一直对DOM的manipulation念念不忘。每次遇到有关的题就看了又看。

Define a walk_the_DOM function that visits every node of the tree in HTML source order, starting from some given node.
  1. 当然是用recursion来做。Each recursive call is given a smaller piece of the tree to work on.
  2. It invokes a function, passing it each node in turn.
  3. walk_the_DOM calls itself to process each of the child nodes.
  4. Code:
Screen Shot 2016-03-22 at 11.46.39 PM.png
Define a getElementsByAttribute function. It takes an attribute name string and an optional matching value.
  1. 利用上面的walk_the_DOM. 传入的是DOM中<body>所在的node,以及一个检查node的attribute是不是和要求的att的value相符合的匿名函数。
  2. 结果存在一个数组里。
  3. Code:Screen Shot 2016-03-22 at 11.46.54 PM.png

你看其实又用到了nodeType的概念所以没文化真可怕啊!

throttling vs. debouncing

每天都在感叹前端水好深,每天都想爬上来写那么一点点。今天被说是卖萌/豆瓣风格的技术博客。I’ll take it as a compliment. 🙂

我跟老爷爷说jQuery有个功能叫debounce的时候他竟然”oh really?!”但是!他最后blahblah讲了应该怎样把keyup event传给setTimeout,然后补充说”which is basically how the debounce is implemented”的时候我断定他之前的惊讶是在唬我!( ̄工 ̄lll)

Continue reading “throttling vs. debouncing”

Everything about DOM

The DOM is short for Document Object Model. But the M in DOM could just as easily stand for Map. Since the DOM is just a MAP of the web page that’s currently loaded in the browser.

  • DOCUMENT = the web page
  • OBJECT = virtual objects
  • MODEL = map

不到两个月前连DOM的数据结构都搞不清楚,现在回想一下被hr羞辱实在是理所应当。后来搞清楚了大致的tree结构然而还是没有理解透彻,以至于上战场后还是做不到举一反三,无法handle一些DOM操作的具体case。真是应该好好从零开始学习。

最近被问到如何实现在一个网页里统计并高亮与查找text match的text。感觉有好多细枝末节啊,比如何时调用函数(我能想到的就是setTimeout,具体怎么应用将来再仔细研究这个javascript函数的时候可以补充);比如一个特别tricky的case,如果我要查找“Hello world”,网页的html里有这么一段:<b>Hello</b> world,这种情况下其实也是符合要求的呀,那怎么办呢?当时就蒙圈啦,难道利用regex么?其实是有种东西叫Node.nodeType的。

比如说

  • Node.ELEMENT_NODE: An Element node such as <p> or <div>
  • Node.TEXT_NODE: The actual Text of Element or Attr

那回到刚才的tricky case是不是就遍历DOM tree中间所有nodeType是TEXT_NODE的node呢。

好厉害啊! Continue reading “Everything about DOM”