Some javascript you may not know artifice

Source: Internet
Author: User
Tags hasownproperty

1. Iterate through an obj attribute to an array

var a=[];  For (A[a.length] in obj); return A;

At first glance may be more Mongolian, but careful analysis is not difficult to understand. The common usage is for (var key in obj), where key is initially undefined, and a[a.length] is undefined, so the two are actually equivalent. In the For loop, the properties of obj are assigned to key in turn, and the same is assigned to A[a.length], where length is changed, and each element of the array is cleverly assigned.

2. Repeating strings (e.g. ABC=>ABCABC)

     function repeat (target,n) {          return (new Array (n+1). Join (target));     }

Modified version:

     function repeat (target,n) {          return Array.prototype.join.call (          {length:n+1},target);//To create an object with the Length property, Because the array prototype method is called, it must be a class array object, and the condition of the class array object is the length is a non-negative integer     }

Instead of creating an array, you replace the object with the Length property, and then call the join method of the array, which improves performance

Further improvements:

     var repeat= (function () {          var join=array.prototype.join,obj={};          return function (target,n) {               obj.length=n+1;               Return Join.call (Obj,target);          }     }) ();

Use closures to cache objects and join methods without creating new objects and finding methods every time.

3, for Loop, when the second item is false will terminate the loop, here is not necessarily a comparison, you can directly assign value, if the assignment is a value such as undefined, the turn to bool value is also false, so it will also terminate, such as traversing an array can be written as:

    for (Var i=arr.length,element;element=arr[--i];) {...}

Here, the second must be arr[--i], not arr[i--], if the latter, up is undefined, will not execute the loop body, or for (Var i=0,element;element=arr[i++];) {...}

4. Nan is the only value in JS that is not equal to itself, so it can be used to determine if a variable is really nan:a!==a.

5, "<", "+" and other operators will force the expression on both sides of the symbol to perform valueof and then compare, so if the two sides are functions or objects, and then rewrite the object's ValueOf method, it will automatically execute the methods on both sides. Such as:

    var a={valueof:function () {console.log ("AAA"),}},b={valueof:function () {Console.log ("BBB");}};    a<b;//will output: aaa;bbb;false;

6, JS has the ability to automatically insert semicolons, but the automatic insertion of semicolons is not omnipotent, there are three rules:

1) is inserted only before the "}" tag, after one or more line breaks, and at the end of the program input;

2) semicolons are inserted only when subsequent input tokens cannot be parsed; This is important, such as: A=b (f ());    is not automatically inserted after a=b, because A=b (f ()) can be parsed, so like "(", "[", "+", "-", "/" at the beginning of the time, you need to pay special attention to the previous row may not be automatically inserted. In some cases, although there will be no parsing errors, JS will still force the insertion of semicolons, which is called the JS grammar limit production.    It does not allow line breaks between two characters, the most dangerous of which is the return statement, such as return {};    will be forcibly inserted and become a return;    {}; Similarly, a throw statement, a break alive continue statement with a display tag, a post-increment or decrement operator 3) semicolon is not automatically inserted as a delimiter in the header of a For loop empty statement Therefore, the best way is to insert the ";" at the very beginning of your own JS file, This will not be a problem when merging JS files. 7, closures. Understanding closures requires learning three basic facts: (1) JS allows you to reference variables that are defined unexpectedly in the current function (2) Even if the external function has returned, the current function can still refer to the variable defined in the external function. This is because the function value of JS contains more information than the code required to execute when calling them (3) Closures can update the values of external variables. This is because closures store references to external variables rather than copies of values. Such as:
function box () {     var val=undefined;     return {          set:function (x) {val=x;},          get:function () {return val;}     };} var b=box (); B.get ();//"Undefined" b.set (5); B.get ();//5

This is important, such as the return of a closure in the function's for loop or the counter value of a closure for a for loop, then the closure is always the final value of I at the end of the for loop, because the closure stores its reference rather than a copy of the value at the time.

8, JS does not have block-level scope, so usually all the variables inside the function are bound to the function scope, that is equivalent to the function is declared at the beginning, an exception is the Try/catch in the variable is block-level, only belongs to the Try/catch block.

9. It is well known that it is possible to declare a function inside a function, but in a local block within a function, the problem may occur:

function f () {return "global";} function test (x) {     function f () {return "local"}     var result=[];     if (x) {          result.push (f ());     }     Result.push (f ());     return result;} Test (true);//["local", "local"]test (false);//["Local"]

Declare the function in the IF block:

function f () {return "global";} function test (x) {     var result=[];     if (x) {          function f () {return "local"}          Result.push (f ());     }     Result.push (f ());     return result;} Test (true);//?test (false);//?
What would be the result? In theory, JS has no block-level scope, so the scope of F () is the entire test function, so a reasonable guess should be the same as the last output, all "local", but not all JS execution environment is doing so, Some will conditionally bind the function f based on whether the code block containing F is executed (binding means binding the variable to its nearest scope, and the assignment occurs when the code actually executes to the assignment). So the best thing to do is to declare a nested function at the outermost layer of its rich function, or not to declare a function, but to use Var declaration and function expression:
function f () {return "global";} function test (x) {     var result=[];     if (x) {          var g=function () {return ' local '}          Result.push (g ());     }     Result.push (f ());     return result;}  

10, when using JS to create a dictionary, if it is the way to use the object (because the core of the JS object is a string attribute name and attribute value mapping table), you will encounter a problem is the prototype pollution, because the dictionary attribute value is hasownproperty OK, if you use for in the loop , not only does it traverse the object itself, including its prototype, so if the prototype of object is contaminated elsewhere, then for-in will produce unintended results, it may be possible to use hasOwnProperty to detect whether the object itself contains properties to avoid prototype contamination. More extreme, however, is the possibility that even hasOwnProperty's prototype method could be contaminated. The way to avoid prototype contamination is to create a fully empty object with object.create (null) when creating the Dictionary object, which is ES5, and it is best to create a dictionary class when no such method is available, and then use an array in the Dictionary class to store an ordered set. Maintain this collection yourself.

11, JS class Array object can enjoy the array of most of the prototype method such as map, class array object is to meet the two conditions of the object: first, with a reasonable range of values within the Length property, the second is the length property is greater than the maximum index of the object, the index is a reasonable range of certificates, Its string represents a key to the object, but a prototype method of the array is not called by the class array object, so it is necessary to first convert the class array object to a real array such as [].slice.call (arguments)] using [].slice.call].

12, not all times need to inherit, inheritance is not perfect, and sometimes create more than he can solve the problem, especially when the level of the relationship is not so obvious, this time should be more structure type (also known as duck type, if it looks like a duck, swimming like a duck and barking like a duck, then it is a duck) , when designing a flexible object interface with a struct type, you do not need to create a class factory to return an instance of the class, but instead return the object directly, with the object having the expected methods and properties, such as:

Someobj.somewidget=function (opts) {     return {          A:blabla,          b:function () {...},          C:blabla     }}

Original link: http://www.cnblogs.com/dson/p/4415278.html

Some javascript you may not know artifice

Related Article

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.