Table of Contents
Directory
条件表达式和等号
注释
空白
逗号
分号
类型转换
命名约定
存取器
构造器
事件
模块
jQuery
ECMAScript 5兼容性
HTML、CSS、JavaScript分离
使用jsHint
前端工具
Home Web Front-end JS Tutorial Very detailed front-end JavaScript specification

Very detailed front-end JavaScript specification

Mar 13, 2017 pm 04:54 PM

JavaScriptSpecification

Directory

  1. Type

  2. Object

  3. Array

  4. String

  5. Function

  6. Attribute

  7. ##Variable

  8. Conditions

    Expressionand equal sign

  9. Block

  10. Comments

  11. Blank

  12. Comma

  13. Semicolon

  14. Type conversion

  15. Naming convention

  16. Accessor

  17. Constructor

  18. Event

  19. Module

  20. jQuery

  21. ES5 Compatibility

  22. HTML, CSS, JavaScript separation

  23. Use jsHint

  24. Front-end tools

Type

  • Original value : Equivalent to passing by value (JavaScript objects all provide literals), using literals to create objects.

    • string<a href="http://www.php.cn/wiki/57.html" target="_blank"></a>

    • ##number

    • boolean

    • null<a href="http://www.php.cn/wiki/62.html" target="_blank"></a>

    • undefined

    • 1

      2

      3

      4

      5

      6

      var foo = 1,

          bar = foo;

       

      bar = 9;

       

      console.log(foo, bar); // => 1, 9

      Copy after login
Complex type

: Equivalent to passing by reference

  • object<a href="http://www.php.cn/wiki/60.html" target="_blank"></a>

  • ##array

    <a href="http://www.php.cn/wiki/58.html" target="_blank"></a>

  • function
  • 1

    2

    3

    4

    5

    6

    var foo = [1, 2],

        bar = foo;

     

    bar[0] = 9;

     

    console.log(foo[0], bar[0]); // => 9, 9

    Copy after login

    Object

Creating objects using literal values

    1

    2

    3

    4

    5

    // bad

    var item = new Object();

     

    // good

    var item = {};

    Copy after login
  • Do not use reserved words as keys
  • 1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    // bad

    var superman = {

      class: &#39;superhero&#39;,

      default: { clark: &#39;kent&#39; },

      private: true

    };

     

    // good

    var superman = {

      klass: &#39;superhero&#39;,

      defaults: { clark: &#39;kent&#39; },

      hidden: true

    };

    Copy after login
  • Array

Use literal values ​​to create arrays

    1

    2

    3

    4

    5

    // bad

    var items = new Array();

     

    // good

    var items = [];

    Copy after login
  • If you don’t know the length of the array, use push
  • 1

    2

    3

    4

    5

    6

    7

    var someStack = [];

     

    // bad

    someStack[someStack.length] = &#39;abracadabra&#39;;

     

    // good

    someStack.push(&#39;abracadabra&#39;);

    Copy after login
  • When you need to copy the array, use slice. jsPerf
  • 1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    var len = items.length,

        itemsCopy = [],

        i;

     

    // bad

    for (i = 0; i < len; i++) {

      itemsCopy[i] = items[i];

    }

     

    // good

    itemsCopy = items.slice();

    Copy after login
  • Use slice to convert array-like objects into arrays.
  • 1

    2

    3

    4

    function trigger() {

      var args = [].slice.apply(arguments);

      ...

    }

    Copy after login
  • String

Use single quotes for strings
    ''
  • (Because most of the time our strings. Especially html will appear

    ")

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    // bad

    var name = "Bob Parr";

     

    // good

    var name = &#39;Bob Parr&#39;;

     

    // bad

    var fullName = "Bob " + this.lastName;

     

    // good

    var fullName = &#39;Bob &#39; + this.lastName;

    Copy after login

    exceeds 80 (there is also a provision of 140, the project can be customized) Strings of characters should use
  • String concatenation
  • Line wrapping

    Note: Long string concatenation may have a performance impact if overused. jsPerf & Discussion
  • 1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    // bad

    var errorMessage = &#39;This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.&#39;;

     

    // bad

    var errorMessage = &#39;This is a super long error that \

    was thrown because of Batman. \

    When you stop to think about \

    how Batman had anything to do \

    with this, you would get nowhere \

    fast.&#39;;

     

    // good

    var errorMessage = &#39;This is a super long error that &#39; +

      &#39;was thrown because of Batman.&#39; +

      &#39;When you stop to think about &#39; +

      &#39;how Batman had anything to do &#39; +

      &#39;with this, you would get nowhere &#39; +

      &#39;fast.&#39;;

    Copy after login
  • Use join instead of string concatenation to build strings when programming, especially IE: jsPerf.
  • 1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    var items,

        messages,

        length, i;

     

    messages = [{

        state: &#39;success&#39;,

        message: &#39;This one worked.&#39;

    },{

        state: &#39;success&#39;,

        message: &#39;This one worked as well.&#39;

    },{

        state: &#39;error&#39;,

        message: &#39;This one did not work.&#39;

    }];

     

    length = messages.length;

     

    // bad

    function inbox(messages) {

      items = &#39;<ul>&#39;;

     

      for (i = 0; i < length; i++) {

        items += &#39;<li>&#39; + messages[i].message + &#39;</li>&#39;;

      }

     

      return items + &#39;</ul>&#39;;

    }

     

    // good

    function inbox(messages) {

      items = [];

     

      for (i = 0; i < length; i++) {

        items[i] = messages[i].message;

      }

     

      return &#39;<ul><li>&#39; + items.join(&#39;</li><li>&#39;) + &#39;</li></ul>&#39;;

    }

    Copy after login
  • Function

    Function expression
  • :

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    // 匿名函数表达式

    var anonymous = function() {

      return true;

    };

     

    // 有名函数表达式

    var named = function named() {

      return true;

    };

     

    // 立即调用函数表达式

    (function() {

      console.log(&#39;Welcome to the Internet. Please follow me.&#39;);

    })();

    Copy after login

    Never declare a function in a non-function block and assign that function to a variable. Browsers allow you to do this, but they parse it differently. A function declaration is not a statement. Read ECMA-262's explanation of this issue.
  • 1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    // bad

    if (currentUser) {

      function test() {

        console.log(&#39;Nope.&#39;);

      }

    }

     

    // good

    if (currentUser) {

      var test = function test() {

        console.log(&#39;Yup.&#39;);

      };

    }

    Copy after login
  • Never name arguments as
  • arguments
  • , this will overstep

    arguments objects passed in the function scope.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    // bad

    function nope(name, options, arguments) {

      // ...stuff...

    }

     

    // good

    function yup(name, options, args) {

      // ...stuff...

    }

    Copy after login

  • Attributes

    When using variables and special When the illegal variable name is used, square brackets can be used when accessing the attribute (.

    takes precedence).
  • 1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    var luke = {

      jedi: true,

      age: 28

    };

     

    function getProp(prop) {

      return luke[prop];

    }

     

    var isJedi = getProp(&#39;jedi&#39;);

    Copy after login

Variable
  • Always use var to declare variables. Failure to do so will result in the creation of global variables. We must avoid polluting the global namespace

    .
  • 1

    2

    3

    4

    5

    // bad

    superPower = new SuperPower();

     

    // good

    var superPower = new SuperPower();

    Copy after login
  • 使用一个 var 以及新行声明多个变量,缩进4个空格。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    // bad

    var items = getItems();

    var goSportsTeam = true;

    var dragonball = &#39;z&#39;;

     

    // good

    var items = getItems(),

        goSportsTeam = true,

        dragonball = &#39;z&#39;;

    Copy after login
  • 最后再声明未赋值的变量,当你想引用之前已赋值变量的时候很有用。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    // bad

    var i, len, dragonball,

        items = getItems(),

        goSportsTeam = true;

     

    // bad

    var i, items = getItems(),

        dragonball,

        goSportsTeam = true,

        len;

     

    // good

    var items = getItems(),

        goSportsTeam = true,

        dragonball,

        length,

        i;

    Copy after login
  • 在作用域顶部声明变量,避免变量声明和赋值引起的相关问题。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    // bad

    function() {

      test();

      console.log(&#39;doing stuff..&#39;);

     

      //..other stuff..

     

      var name = getName();

     

      if (name === &#39;test&#39;) {

        return false;

      }

     

      return name;

    }

     

    // good

    function() {

      var name = getName();

     

      test();

      console.log(&#39;doing stuff..&#39;);

     

      //..other stuff..

     

      if (name === &#39;test&#39;) {

        return false;

      }

     

      return name;

    }

     

    // bad

    function() {

      var name = getName();

     

      if (!arguments.length) {

        return false;

      }

     

      return true;

    }

     

    // good

    function() {

      if (!arguments.length) {

        return false;

      }

     

      var name = getName();

     

      return true;

    }

    Copy after login

条件表达式和等号

  • 合理使用 ===!== 以及 ==!=.

  • 合理使用表达式逻辑操作运算.

  • 条件表达式的强制类型转换遵循以下规则:

    • 对象 被计算为 true

    • Undefined 被计算为 false

    • Null 被计算为 false

    • 布尔值 被计算为 布尔的值

    • 数字 如果是 +0, -0, or NaN 被计算为 false , 否则为 true

    • 字符串 如果是空字符串 &#39;&#39; 则被计算为 false, 否则为 true

      1

      2

      3

      4

      if ([0]) {

        // true

        // An array is an object, objects evaluate to true

      }

      Copy after login
  • 使用快捷方式.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    // bad

    if (name !== &#39;&#39;) {

      // ...stuff...

    }

     

    // good

    if (name) {

      // ...stuff...

    }

     

    // bad

    if (collection.length > 0) {

      // ...stuff...

    }

     

    // good

    if (collection.length) {

      // ...stuff...

    }

    Copy after login
  • 阅读 Truth Equality and JavaScript 了解更多

  • 给所有多行的块使用大括号

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    // bad

    if (test)

      return false;

     

    // good

    if (test) return false;

     

    // good

    if (test) {

      return false;

    }

     

    // bad

    function() { return false; }

     

    // good

    function() {

      return false;

    }

    Copy after login

注释

  • 使用 /** ... */ 进行多行注释,包括描述,指定类型以及参数值和返回值

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    // bad

    // make() returns a new element

    // based on the passed in tag name

    //

    // @param <String> tag

    // @return <Element> element

    function make(tag) {

     

      // ...stuff...

     

      return element;

    }

     

    // good

    /**

     * make() returns a new element

     * based on the passed in tag name

     *

     * @param <String> tag

     * @return <Element> element

     */

    function make(tag) {

     

      // ...stuff...

     

      return element;

    }

    Copy after login
  • 使用 // 进行单行注释,在评论对象的上面进行单行注释,注释前放一个空行.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    // bad

    var active = true;  // is current tab

     

    // good

    // is current tab

    var active = true;

     

    // bad

    function getType() {

      console.log(&#39;fetching type...&#39;);

      // set the default type to &#39;no type&#39;

      var type = this._type || &#39;no type&#39;;

     

      return type;

    }

     

    // good

    function getType() {

      console.log(&#39;fetching type...&#39;);

     

      // set the default type to &#39;no type&#39;

      var type = this._type || &#39;no type&#39;;

     

      return type;

    }

    Copy after login
  • 如果你有一个问题需要重新来看一下或如果你建议一个需要被实现的解决方法的话需要在你的注释前面加上 FIXMETODO 帮助其他人迅速理解

    1

    2

    3

    4

    5

    6

    7

    function Calculator() {

     

      // FIXME: shouldn&#39;t use a global here

      total = 0;

     

      return this;

    }

    Copy after login

    1

    2

    3

    4

    5

    6

    7

    function Calculator() {

     

      // TODO: total should be configurable by an options param

      this.total = 0;

     

      return this;

    }

    Copy after login
  • 满足规范的文档,在需要文档的时候,可以尝试jsdoc.

空白

  • 缩进、格式化能帮助团队更快得定位修复代码BUG.

  • 将tab设为4个空格

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    // bad

    function() {

    ∙∙var name;

    }

     

    // bad

    function() {

    var name;

    }

     

    // good

    function() {

    ∙∙∙∙var name;

    }

    Copy after login
  • 大括号前放一个空格

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    // bad

    function test(){

      console.log(&#39;test&#39;);

    }

     

    // good

    function test() {

      console.log(&#39;test&#39;);

    }

     

    // bad

    dog.set(&#39;attr&#39;,{

      age: &#39;1 year&#39;,

      breed: &#39;Bernese Mountain Dog&#39;

    });

     

    // good

    dog.set(&#39;attr&#39;, {

      age: &#39;1 year&#39;,

      breed: &#39;Bernese Mountain Dog&#39;

    });

    Copy after login
  • 在做长方法链时使用缩进.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    // bad

    $(&#39;#items&#39;).find(&#39;.selected&#39;).highlight().end().find(&#39;.open&#39;).updateCount();

     

    // good

    $(&#39;#items&#39;)

      .find(&#39;.selected&#39;)

        .highlight()

        .end()

      .find(&#39;.open&#39;)

        .updateCount();

     

    // bad

    var leds = stage.selectAll(&#39;.led&#39;).data(data).enter().append(&#39;svg:svg&#39;).class(&#39;led&#39;, true)

        .attr(&#39;width&#39;,  (radius + margin) * 2).append(&#39;svg:g&#39;)

        .attr(&#39;transform&#39;, &#39;translate(&#39; + (radius + margin) + &#39;,&#39; + (radius + margin) + &#39;)&#39;)

        .call(tron.led);

     

    // good

    var leds = stage.selectAll(&#39;.led&#39;)

        .data(data)

      .enter().append(&#39;svg:svg&#39;)

        .class(&#39;led&#39;, true)

        .attr(&#39;width&#39;,  (radius + margin) * 2)

      .append(&#39;svg:g&#39;)

        .attr(&#39;transform&#39;, &#39;translate(&#39; + (radius + margin) + &#39;,&#39; + (radius + margin) + &#39;)&#39;)

        .call(tron.led);

    Copy after login

逗号

  • 不要将逗号放前面

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    // bad

    var once

      , upon

      , aTime;

     

    // good

    var once,

        upon,

        aTime;

     

    // bad

    var hero = {

        firstName: &#39;Bob&#39;

      , lastName: &#39;Parr&#39;

      , heroName: &#39;Mr. Incredible&#39;

      , superPower: &#39;strength&#39;

    };

     

    // good

    var hero = {

      firstName: &#39;Bob&#39;,

      lastName: &#39;Parr&#39;,

      heroName: &#39;Mr. Incredible&#39;,

      superPower: &#39;strength&#39;

    };

    Copy after login
  • 不要加多余的逗号,这可能会在IE下引起错误,同时如果多一个逗号某些ES3的实现会计算多数组的长度。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    // bad

    var hero = {

      firstName: &#39;Kevin&#39;,

      lastName: &#39;Flynn&#39;,

    };

     

    var heroes = [

      &#39;Batman&#39;,

      &#39;Superman&#39;,

    ];

     

    // good

    var hero = {

      firstName: &#39;Kevin&#39;,

      lastName: &#39;Flynn&#39;

    };

     

    var heroes = [

      &#39;Batman&#39;,

      &#39;Superman&#39;

    ];

    Copy after login

分号

  • 语句结束一定要加分号

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    // bad

    (function() {

      var name = &#39;Skywalker&#39;

      return name

    })()

     

    // good

    (function() {

      var name = &#39;Skywalker&#39;;

      return name;

    })();

     

    // good

    ;(function() {

      var name = &#39;Skywalker&#39;;

      return name;

    })();

    Copy after login

类型转换

  • 在语句的开始执行类型转换.

  • 字符串:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    //  => this.reviewScore = 9;

     

    // bad

    var totalScore = this.reviewScore + &#39;&#39;;

     

    // good

    var totalScore = &#39;&#39; + this.reviewScore;

     

    // bad

    var totalScore = &#39;&#39; + this.reviewScore + &#39; total score&#39;;

     

    // good

    var totalScore = this.reviewScore + &#39; total score&#39;;

    Copy after login
  • 对数字使用 parseInt 并且总是带上类型转换的基数.,如parseInt(value, 10)

  • 1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    var inputValue = &#39;4&#39;;

     

    // bad

    var val = new Number(inputValue);

     

    // bad

    var val = +inputValue;

     

    // bad

    var val = inputValue >> 0;

     

    // bad

    var val = parseInt(inputValue);

     

    // good

    var val = Number(inputValue);

     

    // good

    var val = parseInt(inputValue, 10);

     

    // good

    /**

     * parseInt was the reason my code was slow.

     * Bitshifting the String to coerce it to a

     * Number made it a lot faster.

     */

    var val = inputValue >> 0;

    Copy after login
  • 布尔值:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    var age = 0;

     

    // bad

    var hasAge = new Boolean(age);

     

    // good

    var hasAge = Boolean(age);

     

    // good

    var hasAge = !!age;

    Copy after login

命名约定

  • 避免单个字符名,让你的变量名有描述意义。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    // bad

    function q() {

      // ...stuff...

    }

     

    // good

    function query() {

      // ..stuff..

    }

    Copy after login
  • 当命名对象、函数和实例时使用驼峰命名规则

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    // bad

    var OBJEcttsssss = {};

    var this_is_my_object = {};

    var this-is-my-object = {};

    function c() {};

    var u = new user({

      name: &#39;Bob Parr&#39;

    });

     

    // good

    var thisIsMyObject = {};

    function thisIsMyFunction() {};

    var user = new User({

      name: &#39;Bob Parr&#39;

    });

    Copy after login
  • 当命名构造函数或类时使用驼峰式大写

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    // bad

    function user(options) {

      this.name = options.name;

    }

     

    var bad = new user({

      name: &#39;nope&#39;

    });

     

    // good

    function User(options) {

      this.name = options.name;

    }

     

    var good = new User({

      name: &#39;yup&#39;

    });

    Copy after login
  • 命名私有属性时前面加个下划线 _:

    1

    2

    3

    4

    5

    6

    // bad

    this.firstName = &#39;Panda&#39;;

    this.firstName_ = &#39;Panda&#39;;

     

    // good

    this._firstName = &#39;Panda&#39;;

    Copy after login
  • 当保存对 this 的引用时使用 self(<a href="http://www.php.cn/wiki/1514.html" target="_blank">python</a> 风格),避免this issue.Angular建议使用vm(MVVM模式中view-model):

    1

    2

    3

    4

    5

    6

    7

    // good

    function() {

      var self = this;

      return function() {

        console.log(self);

      };

    }

    Copy after login

存取器

  • 属性的存取器函数不是必需的

  • 如果你确实有存取器函数的话使用getVal() 和 setVal(‘hello’),java getter、setter风格或者jQuery风格

  • 如果属性是布尔值,使用isVal() 或 hasVal()

    1

    2

    3

    4

    5

    6

    7

    8

    9

    // bad

    if (!dragon.age()) {

      return false;

    }

     

    // good

    if (!dragon.hasAge()) {

      return false;

    }

    Copy after login
  • 可以创建get()和set()函数,但是要保持一致

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    function Jedi(options) {

      options || (options = {});

      var lightsaber = options.lightsaber || &#39;blue&#39;;

      this.set(&#39;lightsaber&#39;, lightsaber);

    }

     

    Jedi.prototype.set = function(key, val) {

      this[key] = val;

    };

     

    Jedi.prototype.get = function(key) {

      return this[key];

    };

    Copy after login

构造器

  • 给对象原型分配方法,而不是用一个新的对象覆盖原型,覆盖原型会使继承出现问题。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    function Jedi() {

      console.log(&#39;new jedi&#39;);

    }

     

    // bad

    Jedi.prototype = {

      fight: function fight() {

        console.log(&#39;fighting&#39;);

      },

     

      block: function block() {

        console.log(&#39;blocking&#39;);

      }

    };

     

    // good

    Jedi.prototype.fight = function fight() {

      console.log(&#39;fighting&#39;);

    };

     

    Jedi.prototype.block = function block() {

      console.log(&#39;blocking&#39;);

    };

    Copy after login
  • 方法可以返回 this 帮助方法可链。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    // bad

    Jedi.prototype.jump = function() {

      this.jumping = true;

      return true;

    };

     

    Jedi.prototype.setHeight = function(height) {

      this.height = height;

    };

     

    var luke = new Jedi();

    luke.jump(); // => true

    luke.setHeight(20) // => undefined

     

    // good

    Jedi.prototype.jump = function() {

      this.jumping = true;

      return this;

    };

     

    Jedi.prototype.setHeight = function(height) {

      this.height = height;

      return this;

    };

     

    var luke = new Jedi();

     

    luke.jump()

      .setHeight(20);

    Copy after login
  • 可以写一个自定义的toString()方法,但是确保它工作正常并且不会有副作用。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    function Jedi(options) {

      options || (options = {});

      this.name = options.name || &#39;no name&#39;;

    }

     

    Jedi.prototype.getName = function getName() {

      return this.name;

    };

     

    Jedi.prototype.toString = function toString() {

      return &#39;Jedi - &#39; + this.getName();

    };

    Copy after login

事件

  • 当给事件附加数据时,传入一个哈希而不是原始值,这可以让后面的贡献者加入更多数据到事件数据里而不用找出并更新那个事件的事件处理

    1

    2

    3

    4

    5

    6

    7

    8

    // bad

    $(this).trigger(&#39;listingUpdated&#39;, listing.id);

     

    ...

     

    $(this).on(&#39;listingUpdated&#39;, function(e, listingId) {

      // do something with listingId

    });

    Copy after login

    更好:

    1

    2

    3

    4

    5

    6

    7

    8

    // good

    $(this).trigger(&#39;listingUpdated&#39;, { listingId : listing.id });

     

    ...

     

    $(this).on(&#39;listingUpdated&#39;, function(e, data) {

      // do something with data.listingId

    });

    Copy after login

模块

  • 这个文件应该以驼峰命名,并在同名文件夹下,同时导出的时候名字一致

  • 对于公开API库可以考虑加入一个名为noConflict()的方法来设置导出的模块为之前的版本并返回它

  • 总是在模块顶部声明 &#39;use strict&#39;;,引入[JSHint规范](http://www.php.cn/):

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    // fancyInput/fancyInput.js

     

    function(global) {

      &#39;use strict&#39;;

     

      var previousFancyInput = global.FancyInput;

     

      function FancyInput(options) {

        this.options = options || {};

      }

     

      FancyInput.noConflict = function noConflict() {

        global.FancyInput = previousFancyInput;

        return FancyInput;

      };

     

      global.FancyInput = FancyInput;

    })(this);

    Copy after login

jQuery

  • 对于jQuery对象以$开头,以和原生DOM节点区分。

    1

    2

    3

    4

    5

    // bad

    var menu = $(".menu");

     

    // good

    var $menu = $(".menu");

    Copy after login
  • 缓存jQuery查询

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    // bad

    function setSidebar() {

      $(&#39;.sidebar&#39;).hide();

     

      // ...stuff...

     

      $(&#39;.sidebar&#39;).css({

        &#39;background-color&#39;: &#39;pink&#39;

      });

    }

     

    // good

    function setSidebar() {

      var $sidebar = $(&#39;.sidebar&#39;);

      $sidebar.hide();

     

      // ...stuff...

     

      $sidebar.css({

        &#39;background-color&#39;: &#39;pink&#39;

      });

    }

    Copy after login
  • 对DOM查询使用级联的 $(&#39;.sidebar ul&#39;)$(&#39;.sidebar ul&#39;),jsPerf

  • 对有作用域的jQuery对象查询使用 find:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    // bad

    $(&#39;.sidebar&#39;, &#39;ul&#39;).hide();

     

    // bad

    $(&#39;.sidebar&#39;).find(&#39;ul&#39;).hide();

     

    // good

    $(&#39;.sidebar ul&#39;).hide();

     

    // good

    $(&#39;.sidebar > ul&#39;).hide();

     

    // good (slower)

    $sidebar.find(&#39;ul&#39;);

     

    // good (faster)

    $($sidebar[0]).find(&#39;ul&#39;);

    Copy after login
  • 每个页面只使用一次document的ready事件,这样便于调试与行为流跟踪。

    1

    2

    3

    $(function(){

       //do your page init. 

    });

    Copy after login
  • 事件利用jQuery.on从页面分离到JavaScript文件。

    1

    2

    3

    4

    5

    6

    7

    // bad

    <a id="myLink" href="#" onclick="myEventHandler();"></a>

     

    // good

    <a id="myLink" href="#"></a>

     

    $("#myLink").on("click", myEventHandler);

    Copy after login
  • 对于Ajax使用promise方式。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    // bad

       $.ajax({

           ...

           success : function(){

           },

           error : function(){

           }

       })

     

       // good

       $.ajax({.

           ..

       }).then( function( ){

           // success

       }, function( ){

           // error

       })

    Copy after login
  • 利用promise的deferred对象解决延迟注册问题。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    var dtd = $.Deferred(); // 新建一个deferred对象

      var wait = function(dtd){

        var tasks = function(){

          alert("执行完毕!");

          dtd.resolve(); // 改变deferred对象的执行状态

        };

        setTimeout(tasks,5000);

        return dtd;

      };

    Copy after login
  • HTML中Style、以及JavaScript中style移到CSS中class,在HTML、JavaScript中引入class,而不是直接style。

ECMAScript 5兼容性

尽量采用ES5方法,特别数组map、filter、forEach方法简化日常开发。在老式IE浏览器中引入ES5-shim。或者也可以考虑引入underscore、lodash 常用辅助库.
- 参考Kangax的 ES5 compatibility table

HTML、CSS、JavaScript分离

  • 页面DOM结构使用HTML,样式则采用CSS,动态DOM操作JavaScript。不要混用在HTML中

  • 分离在不同类型文件,文件link。

  • HTML、CSS、JavaScript变量名都需要有业务价值。CSS以中划线分割的全小写命名,JavaScript则首字母小写的驼峰命名。

  • CSS可引入Bootstrap、Foundation等出名响应式设计框架。以及SASS、LESS工具书写CSS。

  • 对于CSS、JavaScript建议合并为单文件,减少Ajax的连接数。也可以引入AMD(Require.js)加载方式。

  • 对于内部大部分企业管理系统,可以尝试采用前端 MVC框架组织代码。如Angular、React + Flux架构、Knockout等。

  • 对于兼容性可用Modernizr规范库辅助。

使用jsHint

  • 前端项目中推荐引入jshint插件来规范项目编码规范。以及一套完善的IDE配置。

  • 注意:jshint需要引入nodejs 工具grunt或gulp插件,建议企业级nodejs npm私服。

前端工具

  • 前端第三方JavaScript包管理工具bower(bower install jQuery),bower可以实现第三方库的依赖解析、下载、升级管理等。建议建立企业级bower私服。

  • 前端构建工具,可以采用grunt或者gulp工具,可以实现html、css、js压缩、验证、测试,文件合并、watch和liveload等所有前端任务。建议企业级nodejs npm私服。

  • 前端开发IDE: WebStorm( Idea )、Sublime为最佳 。项目组统一IDE。IDE统一配置很重要。


The above is the detailed content of Very detailed front-end JavaScript specification. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django: A magical framework that can handle both front-end and back-end development! Django: A magical framework that can handle both front-end and back-end development! Jan 19, 2024 am 08:52 AM

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

See all articles