简体   繁体   English

此JavaScript代码没有错误,但无法正常工作。 有看不到的秘密错误吗?

[英]There is no error with this javascript code yet it does not work. Is there a secret error I can't see?

I have this JavaScript code I've been using for weeks now and no error has ever occurred with it but now all of a sudden it just doesn't work! 我有我已经使用了几周的JavaScript代码,并且从未发生过任何错误,但是突然之间,它根本无法正常工作! Here is the code itself: 这是代码本身:

 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"); 

If you're executing this code in the global scope, name already exists as window.name . 如果要在全局范围内执行此代码,则name已经作为window.name存在。 Therefore, name = new DB("Names DB") coerces the second half into a string and you essentially run name = '[object Object]' . 因此, name = new DB("Names DB")将后半部分强制转换为字符串,并且实际上运行了name = '[object Object]'

Wrap everything in a function to use a non-global scope: 将所有内容包装在函数中以使用非全局范围:

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

Or choose a different variable name. 或选择其他变量名称。

That code is in conflict with attribute window.name you need to enclose your code in a function or drastically remove the attribute name from window object. 该代码与属性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'); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM