简体   繁体   中英

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

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

Sorry for my poor English and my noob level on 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.

You can use a different name (like "naem") and things should work fine. Of course, there's the risk of picking a name that's already in use as another intrinsic of the window object. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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