JavaScript Patterns 2.7 Avoiding Implied Typecasting

Dealing with == and ===

false == 0 or "" == 0 return true.

always use the === and !==

operators that check both the values and the type of the expressions you
compare:


var zero = 0;
if (zero === false) {
// not executing because zero is 0, not false
}

// antipattern
if (zero == false) {
// this block is executed...
}   

Avoiding eval()


// antipattern

var property = "name";
alert(eval("obj." + property));

// preferred

var property = "name";
alert(obj[property]);

Security implications (e.g. JSON response from an Ajax
request)

1. For browsers that don‘t support JSON.parse() natively,
you can use a library from JSON.org.

2. passing strings to setInterval(), setTimeout(), and the Function()
constructor is, for the most part, similar to using eval()and therefore should
be avoided.


// antipatterns

setTimeout("myFunc()", 1000);
setTimeout("myFunc(1, 2, 3)", 1000);

// preferred

setTimeout(myFunc, 1000);
setTimeout(function () {
myFunc(1, 2, 3);
}, 1000);   

3. Using the new Function() constructor is similar to eval()
and should be approached with care.

    1. If you absolutely must use eval(), you can consider using new
      Function()
      instead.
      Because the code evaluated in new
      Function() will be running in a local function scope, so any variables
      defined with var in the code being evaluated will
      not
      become globals automatically.

    2. Or wrap the eval() call into an immediate function.


      console.log(typeof un); // "undefined"

      console.log(typeof deux); // "undefined"

      console.log(typeof trois); // "undefined"

      var jsstring = "var un = 1; console.log(un);";

      eval(jsstring); // logs "1"

      jsstring = "var deux = 2; console.log(deux);";

      new Function(jsstring)(); // logs "2"

      jsstring = "var trois = 3; console.log(trois);";

      (function () {

      eval(jsstring);

      }()); // logs "3"

      console.log(typeof un); // "number"

      console.log(typeof deux); // "undefined"

      console.log(typeof trois); // "undefined"


    3. No matter where you execute Function, it sees only the
      global scope. So it can do less local variable pollution.


       (function () {

      var local = 1;

      eval("local = 3; console.log(local)"); // logs 3

      console.log(local); // logs 3

      }());

      (function () {

      var local = 1;

      Function("console.log(typeof local);")(); // logs undefined

      }());

JavaScript Patterns 2.7 Avoiding Implied Typecasting

时间: 2024-10-16 16:50:39

JavaScript Patterns 2.7 Avoiding Implied Typecasting的相关文章

JavaScript Patterns 2.2 - Minimizing Globals

Access a global variable in a browser environment: myglobal = "hello"; // antipattern console.log(myglobal); // "hello" console.log(window.myglobal); // "hello" console.log(window["myglobal"]); // "hello"

JavaScript Patterns 2.6 switch Pattern

Principle ? Aligning each case with switch(an exception to the curly braces indentation rule). ? Indenting the code within each case. ? Ending each case with a clear break;. ? Avoiding fall-throughs (when you omit the break intentionally). If you're

JavaScript Patterns 5.4 Module Pattern

MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var uobj = MYAPP.utilities.object, ulang = MYAPP.utilities.lang, // private properties array_string = "[object Array]", ops = Object.prototype.toStr

JavaScript Patterns 3.7 Primitive Wrappers

Primitive value types: number, string, boolean, null, and undefined. // a primitive number var n = 100; console.log(typeof n); // "number" // a Number object var nobj = new Number(100); console.log(typeof nobj); // "object"  One reason

JavaScript Patterns 2 Essentials - Writing Maintainable Code

Revisiting the code after some time has passed requires: ? Time to relearn and understand the problem ? Time to understand the code that is supposed to solve the problem As the application matures, many other things happen that require your code to b

JavaScript Patterns 7.1 Singleton

7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. This means that the second time you use the same class to create a new object, you should get the same object that was created the first time. var obj =

JavaScript Patterns 2.12 Writing API Docs

Free and open source tools for doc generation: the JSDoc Toolkit (http://code.google.com/p/jsdoc-toolkit/) and YUIDoc (http://yuilibrary.com/projects/yuidoc). Process of generating API documentation ? Writing specially formatted code blocks ? Running

JavaScript Patterns 2.11 Writing Comments

Document all functions, their arguments and return values, and also any interesting or unusual algorithm or technique. Think of the comments as hints to the future readers of the code; the readers need to understand what your code does without readin

JavaScript Patterns 4.7 Init-Time Branching

When you know that a certain condition will not change throughout the life of the program, it makes sense to test the condition only once. Browser sniffing (or feature detection) is a typical example. // BEFORE var utils = { addListener : function(el