JavaScript code snippets

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.