zoukankan      html  css  js  c++  java
  • JavaScript Best Practices

    原文: https://www.w3schools.com/js/js_best_practices.asp

    ----------------------------------------------

    Avoid global variables,  avoid new,  avoid  ==,  avoid eval()


    Avoid Global Variables

    Minimize the use of global variables.

    This includes all data types, objects, and functions.

    Global variables and functions can be overwritten by other scripts.

    Use local variables instead, and learn how to use closures.


    Always Declare Local Variables

    All variables used in a function should be declared as local variables.

    Local variables must be declared with the var keyword, otherwise they will become global variables.

    Strict mode does not allow undeclared variables.


    Declarations on Top

    It is a good coding practice to put all declarations at the top of each script or function.

    This will:

    • Give cleaner code
    • Provide a single place to look for local variables
    • Make it easier to avoid unwanted (implied) global variables
    • Reduce the possibility of unwanted re-declarations
    // Declare at the beginning
    var firstName, lastName, price, discount, fullPrice;

    // Use later
    firstName = "John";
    lastName = "Doe";

    price = 19.90;
    discount = 0.10;

    fullPrice = price * 100 / discount;

    This also goes for loop variables:

    // Declare at the beginning
    var i;

    // Use later
    for (i = 0; i < 5; i++) {
  • 相关阅读:
    2019春季第五周作业
    2019春第四周作业(基础题)计算机
    2019第三周作业
    第二周基础作业
    2019春第九周作业
    2019年春第八周作业
    第七周总结
    第六周作业
    2019春第五周作业
    2019年春季学期第四周作业
  • 原文地址:https://www.cnblogs.com/oxspirt/p/9115537.html
Copyright © 2011-2022 走看看