I'm trying to clean up a long-standing bad habit in coding: widgets writing in the global scope.
I have created a large, mostly self-contained script for a news roll on a webpage and it is completely amazed that how well I filled the whole thing in the function ... a very good thing is.
To ensure that I was not cheated, I had written the following code to ensure that my scroll was correct:
var story_count = "This one Number is not "; Console.log (story_count); Touch_roll = function () {this.story_count = 0; } Console.log (story_count); Touch_roll (); Console.log (story_count); There is a complete hope of giving the following feedback in the console
This is not a number. It is not a number. It is not a number < / Pre> I think the output was really amazing, in fact, it : this is not a number. It is not a number 0 < / Code> what is this is not what I think? Research has not really helped, but I have been burned a bit, so it is entirely possible that I am reading it all wrong. If not, then how do I keep all my names completely within the scope of that function, so that the site does not mess with existing bits?
According to the answer given below, correct code here:
var story_count = "this is not a number"; Console.log (story_count); Var touch_roll = new function () {this.story_count = 0; Console.log (story_count); } Console.log (story_count); By declaring touch_roll as var and adding the function as new is. The object in the form of run-time (so we can remove the call at touch_roll () below.) The correct output is as follows:
This is not a number. 0 This is not a number
Because you ' Touch_roll with new , this is window object (which is the global variable in my browser environment). If you want to use the new , you will get: this is not a number. This is not a number, it is not Additionally, you are declaring touch_roll as an inherent global variable, or use it either, or use a var < / Code> add.
Comments
Post a Comment