【问题标题】:There is no error with this javascript code yet it does not work. Is there a secret error I can't see?此 javascript 代码没有错误,但它不起作用。有我看不到的秘密错误吗?
【发布时间】:2018-08-04 03:51:51
【问题描述】:

我有这个 JavaScript 代码,我已经使用了好几个星期了,它从来没有发生过错误,但现在突然之间它就不起作用了!这是代码本身:

function DB(name) {
  this.name = name;
  this.content = [];
  this.add = function(value) {
    this.content.push(value);
  }
  this.get = function(id) {
    return this.content[id];
  } 
}

var name = new DB("Names DB");

name.add("Test Name");

【问题讨论】:

    标签: javascript arrays html object error-handling


    【解决方案1】:

    如果您在全局范围内执行此代码,name 已作为 window.name 存在。因此,name = new DB("Names DB") 将后半部分强制转换为字符串,而您实际上是在运行 name = '[object Object]'

    将所有内容包装在一个函数中以使用非全局范围:

    (function() {
        // Your code
    })();
    

    或者选择一个不同的变量名。

    【讨论】:

    • 哇我不知道有这样的变量!非常感谢!
    【解决方案2】:

    该代码与属性window.name 冲突,您需要将代码包含在函数中或从window 对象中彻底删除属性name

    delete window.name; // Remove attribute.
    
    function DB(name) {
      this.name = name;
      this.content = [];
    
      this.add = function(value) {
        this.content.push(value);
      }
    
      this.get = function(id) {
        return this.content[id];
      }
    }
    
    var name = new DB("Names DB");
    name.add('Test Name');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 2020-04-08
      相关资源
      最近更新 更多