Javascript (六):Know 'Closure' Inside Out?

What is closure?

In JavaScript, closures are often regarded as some sort of magical unicorn that only advanced developers can really understand, but truth be told it is just a simple understanding of the scope chain. A closure, as Douglas Crockford says, is simply:

An inner function always has access to the vars and parameters of its outer function, even after the outer function has returned…

The code below is an example of a closure:

// ==>进入全局执行上下文
var dongcCard = card('dongc');

dongcCard();

function card(sname) {
    var gender = 'male';
    return function showInfo() {
        console.log('[carInfo] name:%s gender:%s', sname, gender);
    }
}

read above code , have two doubts:

  • 为何card函数在定义之前,可以被调用?
  • 为何card函数执行完毕后,card函数中“gender”属性仍然可以被访问?

究其原由,深入内核底层,一探究竟。

How do javascript engine work?

The JavaScript interpreter in a browser is implemented as a single thread. Actions or Events being queued in what is called the execution stack. The diagram below is an abstract view of a single threaded stack: ecstack Read More...

Refactor (一) :Refactor As A Routine Work

What refactor ?

Refactoring is done to fill in short-cuts, eliminate duplication and dead code, and to make the design and logic clear.Always to simplify the code and to make it easier to understand. Always to make it easier and safer to change in the future.

Why refactor ?

  • 代码写得脏

可读性差、逻辑不清,导致问题不断,阻碍快速迭代开发。

迫于“时间紧迫、需求易变、编码能力”,那时那刻“思路不清晰地写出“不堪入目”代码。

  • 框架单薄,无力支持

随着业务量增加,现有的架构太单薄,无力支持庞大的业务量,不得不“Large Scale Refactoring”。

How refactor ?

  • Confirm your understanding of code

首先弄懂代码、增加必要注释。针对业务复杂的,借助UML梳理业务

  • Make refactor safe

Regression test your refactoring work and Reviewing all of these changes , ensure that you haven’t changed the behavior – it still works the same.

Read More...

Java (二):Tired Of Null Pointer Exception

Brief

A wise man once said you are not a real Java programmer until you’ve dealt with a null pointer exception. 没有处理过空指针,不算是真正的JAVA程序员

A NullPointerException at runtime and stop your program from running further.imagine if your program was running on a customer’s machine; what would your customer say if the program suddenly failed?

To give some historical context, Tony Hoare—one of the giants of computer science—wrote, “I call it my billion-dollar mistake. It was the invention of the null reference in 1965. I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement.

空指针造成十亿美元的损失 Let’s start with an example to see the dangers of Null. a nested object structure for a Computer, as illustrated:

OPTIONAL

 

String version = computer.getSoundcard().getUsb().getVersion();

How do avoid making NullPointerException ?

Read More...