1. template replacement (learned from crockford)
VaR template = '<Table border = "{border}">' + '<tr> <TH> last </Th> <TD> {last} </TD> </ tr> '+' <tr> <TH> first </Th> <TD> {First} </TD> </tr> '+' </table> 'var data = {first: 'Jerry ', last: 'chou', border: 2} mydiv. innerhtml = template. supplant (data); // implement if (typeof string. prototype. supplant! = 'Function') {string. prototype. supplant = function (o) {return this. replace (/{([^ {}])}/g, function (a, B) {var r = O [B]; return typeof r = 'string '? R: ;}}}
2. Simulate block Scope)
We know that there is no block scope in Javascript, and all variables defined in the function body will be hoisting (that is, the top of the function ). To simulate block scope similar to C/Java/C #, we can use the followingCodeFragment. This is also a common form of class libraries written by others, such as jquery-called immediately after definition.
(Function () {// bla .. bla }());
For example, the following code uses this technology to simulate a block scope:
Function Foo () {var x = 1; if (x) {(function () {var x = 2; // some other code }());} // X is still 1 .}
Why do I define a function scope to call immediately? Because the function definition does not execute code on the function body, when you add () after the function definition, to execute the code in the function body. A more rigorous statement is that the execution environment (Execution context) will be created only when the function is called (plus ).
Reference: [translation] JavaScript scoping and hoisting