JavaScript插件,Node是Object,应该是HTMLElement吗?

时间:2017-09-25 12:11:58

标签: javascript

我有以下(针对此问题简化)插件,node值是options.container的值,它是一个HTMLObject但是当我在其上键入Object时返回。

这是一个问题,因为当我尝试使用数据集值覆盖它时,我检测到它的类型并相应地替换它。

// Define option defaults
  constructor(node) {
    const _ = this;

    var options = {
      container: node,
    };

    (function() {
      for( const data in node.dataset ) {
        var key = (data.replace("map", "")).charAt(0).toLowerCase() + (data.replace("map", "")).substr(1), 
            value = node.dataset[data];

        // Check the value has been set
        if (value !== '') {
          switch(typeof options[key]) {
            case 'object':
              options[key] = JSON.parse(value);
            break;
            case 'HTMLElement':
              options[key] = value.GetElement();
            break;
            default:
              options[key] = value;
            break;
          }
        }
      }

      console.log(options);
    }.call(_));


    // Initialize the map
    // this.init();
  };

  static init(node) {
    return new this(node);
  }
  static initAll(node) {
    var _ = this,
      instances = [];

    window.addEventListener('load', function () {
      var maps = document.querySelectorAll('[data-map]');
      var current = [];
      var InitializeMap = function (e) {
        instances.push(_.init(e)); // Setup new instance of this class for each map
      };

      // Keep a reference for each map
      for (var i = 0; i < maps.length; i++) {
        var dataset = maps[i].dataset;
        if (current.indexOf(dataset.googleMap) === -1) {
          current.push(dataset.googleMap);
          InitializeMap(maps[i]);
        }
      }
    });

    return instances;
  }

正如您在下面的代码中看到的,我得到一个名为data.map.container的属性,其中包含#map_container的值。因此,在switch函数期间,我需要检测node值是HTMLObject而不是object

对于记录,我做console.log(options.container)然后HTMLElement显示在日志中。

P.S。 GetElement()只接受字符串并返回HTMLObject,因此#element将执行getElementById,而.element将执行getElementByClassName。只是我的jQuery版本的$()。

1 个答案:

答案 0 :(得分:1)

typeof无法告知此类特定对象类型,请参阅可能的返回值:https://developer.mozilla.org/hu/docs/Web/JavaScript/Reference/Operators/typeof

您可以使用instanceof来检查您需要的课程。