[英]There is no error with this javascript code yet it does not work. Is there a secret error I can't see?
我有我已经使用了几周的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");
如果要在全局范围内执行此代码,则name
已经作为window.name
存在。 因此, name = new DB("Names DB")
将后半部分强制转换为字符串,并且实际上运行了name = '[object Object]'
。
将所有内容包装在函数中以使用非全局范围:
(function() {
// Your code
})();
或选择其他变量名称。
该代码与属性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.