简体   繁体   English

为什么我不能使用全局变量中的对象函数?

[英]Why I can't use object functions from a global variable?

Hello everyone ^^ 大家好^^
I want to use functions for create inputs, but like objects (for create customizable inputs), after that, assign them to a variable, for example "name". 我想使用函数来创建输入,但是像对象(用于创建可自定义的输入)之后,将它们分配给变量,例如“名称”。 After that i want to use their functions (create and check) the first one insert an input in the div "userInfo" at the HTML code and the second one check the value inside input 之后,我想使用它们的功能(创建和检查),第一个在HTML代码的div“ userInfo”中插入输入,第二个检查输入中的值

The problem is when I assign an object to the global variable "name" and after that I use their functions, the console of the browsers tell me that name.create() is not a function and I can't use it 问题是当我将对象分配给全局变量“名称”时,然后使用它们的函数,浏览器的控制台告诉我name.create()不是函数,我不能使用它

Sorry for my poor English and my noob level on JavaScript xD 对不起,我的英语很差,并且在JavaScript xD上的菜鸟水平也很低
Thanks to Everybody ^^ 谢谢大家^^

 function createAll() { name = new textInput("nameInput", 8, 24, "a-Z0-9", "required"); concatFirst += name.create(); document.getElementById("userInfo").innerHTML = concatFirst; console.log(JSON.stringify(name)); } function textInput(idInput, minlenght, maxlenght, req, requiredOption) { this.idIn = idInput; this.minLong = minlenght; this.maxLong = maxlenght; this.reqCha = req; this.requiredOpt = requiredOption; this.create = function () { return "<p> \\ <input id='" + this.idIn + "' pattern='[" + this.reqCha + "]{" + this.minLong + ",}' maxlenght='" + this.maxLong + "' " + " onchange='name.check()' onmouseover='name.check()' " + this.requiredOpt + " ></input> \\ </p>"; } this.check = function () { document.getElementById(this.idIn).style.boxShadow = "0 0 10px 3px green"; } } 
 <html> <body onload="createAll();"> <div id="mainForm"> <!-- First Form --> <div id="userInfo"> </div> </div> </body> </html> 

The global symbol "name" is an intrinsic property of the window object, and browsers won't let you change it to anything but a string. 全局符号“名称”是window对象的固有属性,浏览器不允许您将其更改为字符串以外的任何内容。

You can use a different name (like "naem") and things should work fine. 您可以使用其他名称(例如“ naem”),并且一切正常。 Of course, there's the risk of picking a name that's already in use as another intrinsic of the window object. 当然,存在选择一个已经用作window对象的另一个内在名称的风险。 This whole situation is a good object lesson on why global variables in JavaScript client code are undesirable: the environment is a minefield of potential conflicts like the one you've hit upon. 总体情况是一个很好的目标课程,它说明了为什么不希望JavaScript客户端代码中的全局变量:环境是潜在冲突的雷区,就像您遇到的那样。

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

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