2.4.4 不足

虽然Bootstrap为我们提供了丰富多彩的插件,但是其插件代码在编程规范上却存在很多不足。这里所谓的不足是指:虽然编译器可以识别这些代码,但它不符合大多数JavaScript开发者所使用的规范。Bootstrap中不规范的代码示例如下:

  1. var Modal = function (element, options) {
  2. this.options = options // 这里少了分号
  3. this.$element = $(element).delegate('[data-dismiss="modal"]', 'click.dismiss.
  4. modal', $.proxy(this.hide, this)) // 这里少了分号
  5. this.$backdrop = // 这里使用了链式赋值,其值是this.isShown的null值
  6. this.isShown = null // 这里少了分号
  7.  
  8. if (this.options.remote) this.$element.find('.modal-body').load(this.options.
  9. remote)
  10. // if语句应该用花括号括住
  11. }

通过注释大家可以发现,其中省略了很多分号,并且使用了简便方法。虽然现代的JavaScript解释器会对这样的代码进行正常解释,但是其可读性变差。建议在编写自定义插件的时候参照如下示例代码:

  1. var Modal = function (element, options) {
  2. this.options = options;
  3. this.$element = $(element).delegate('[data-dismiss="modal"]', 'click.dismiss.modal',
  4. $.proxy(this.hide, this)); // 复杂的语句最好有点注释
  5. this.$backdrop = "";
  6. this.isShown = null;
  7. if (this.options.remote) {
  8. this.$element.find('.modal-body').load(this.options.remote);
  9. }
  10. }