Global variable not defined from onclick? - javascript

I have declared my array globally like so:
window.onload = function(){
var test = 'test';
var sel = new Array();
login_check();
};
Everything pretty much is inherited from login_check() function in my engine. The problem is whilst var test is set var sel is not set when i use it in a function.
I use this in my function :
console.log(test); //displays as intended
if(sel.length > 0){ //ERROR Uncaught ReferenceError: sel is not defined
//do something
}
I should mention sel is normally empty at this point. Does JS some how not allow global arrays to be set?

I advice to move the variables outside the function e.g.
var test;
var sel;
window.onload = function(){
test = 'test';
sel = new Array();
login_check();
};

Instead make it truly global:
window.onload = function(){
var window.test = 'test';
var window.sel = new Array();
login_check();
};
And in the function:
console.log(window.test); //displays as intended
if(window.sel.length > 0) {
//do something
}
If still the same problem, it might be due to this, as window.sel is an empty array, it can be considered as null.
Try another method to keep the variable declaration out of the function:
var test;
var sel;
window.onload = function(){
test = 'test';
sel = new Array();
login_check();
};

To make the Objects/Variables Global you can use the simple method Of declaring it outside the function block
sample
var test;
var sel;
window.onload = function(){
test = 'test';
sel = new Array();
login_check();
};
Hope this helps!

Related

Copy object functions and properties in new object by value not by reference - javascript

I want to copy the functions and properties of an object into new object. The old object should not effect by changing made in new Object.
Here is the object definition:
var Call = function() {
this.number="123";
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
I can access function1 using callobj.function1().
What I have tried to copy it:
Javascript:
var newcallobj = Object.assign({}, callobj);
In this case, i am not able to access function1 but i can access number property directly.
JQUERY:
var newObj = jQuery.extend(true, {}, callobj); OR
var newObj = jQuery.extend({}, callobj);
In this case, i am able to access function1 and property but when i change number like that newObj.number="222". It also change the value of original object.
I know that there is couple of other posts. But all is not working for me. Please let me know if i am doing any thing wrong?
AFTER #gurvinder372 answer(I am updating question):
After #gurvinder372 answer. It is working for first level of property but if it has another object like i show below and i change the value of property of another object. Then it is effecting on original object also.
var ABC = function(){
this.number = "333";
}
var Call = function() {
this.number="123";
this.anotherobj = new ABC();
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
newcallobj.anotherobj.number= "123";
console.log(newcallobj.anotherobj.number);
console.log(callobj.anotherobj.number);
Output of both is 123. #gurvinder372. can you check th above code ?
Object.assign only copies the enumerable properties of an object.
Use Object.create instead of Object.assign
var newcallobj = Object.create(callobj);
var Call = function() {
this.number="123";
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
console.log(newcallobj.function1());
Ok. By the help of #gurvinder372. The following solution is working for me.
var ABC = function(){
this.number = "333";
}
var Call = function() {
this.number="123";
this.anotherobj = new ABC();
}
Call.prototype.function1 = function() {
return this.number;
}
var callobj = new Call();
var newcallobj = Object.create(callobj);
newcallobj.anotherobj = Object.create(callobj.anotherobj);
newcallobj.anotherobj.number= "123";
console.log(newcallobj.anotherobj.number);
console.log(callobj.anotherobj.number);
Please let me know if there is any better solution other than this?

JS encapsulation issue: "this.foo = new function(){...};" vs "this.Bar = function(){..}; this.foo = new Bar();"

Not entirely sure why one works and the other does not. Could someone please explain this? I'm new to JavaScript. I've been reading this guide so far.
This works. Data is considered to be a local variable of the _fSettings object.
ENTRANCE_APP._fSettings = function(){
var data = new StorageObject('settings');
/** The selected camera index. **/
var cameraIndex = data.getValue('cameraIndex','0');
this.setCameraIndex = function(index) {cameraIndex = index;};
this.getCameraIndex = function() {return cameraIndex;};
};
ENTRANCE_APP.settings = new ENTRANCE_APP._fSettings();
But this does not? data is considered to be a global variable after that first declaration. So 'data.getValue(...)' treats data as a global variable.
ENTRANCE_APP.settings = new function(){
var data = new StorageObject('settings');
/** The selected camera index. **/
var cameraIndex = data.getValue('cameraIndex','0');
this.setCameraIndex = function(index) {cameraIndex = index;};
this.getCameraIndex = function() {return cameraIndex;};
};
Try treating it as an IIFE like this:
ENTRANCE_APP.settings = new (function(){
var data = new StorageObject('settings');
/** The selected camera index. **/
var cameraIndex = data.getValue('cameraIndex','0');
this.setCameraIndex = function(index) {cameraIndex = index;};
this.getCameraIndex = function() {return cameraIndex;};
})();
Notice the parentheses surrounding the function to create a function expression and the parentheses after it to invoke the function.

Javascript object instance and document ready

This code gives me an error:
$(function(){
var instance = new object();
literal.call();
});
var literal ={
call : function(){
instance.foo();
}
}
function object(){
this.selector = $('div');
this.foo = function(){ this.selector.remove(); }
}
I want to make it run and I want to let the literal object out from $(function(){}). I don't want to change the selector at a later time.
So I discarded this solution
$(function(){
instance.selector = $('div');
literal.call();
});
var instance = new object();
var literal ={
call : function(){
instance.foo();
}
}
function object(){
this.selector = $('div');
this.foo = function(){ this.selector.remove(); }
}
And I discarded this also
$(function(){
var instance = new object();
var literal ={
call : function(){
instance.foo();
}
}
literal.call();
});
function object(){
this.selector = $('div');
this.foo = function(){ this.selector.remove(); }
}
what is the best practice to do this?
Your problem is that the istance variable was local to the ready handler. As you don't want to move your code in there (for whatever reasons), you will need to make the variable global:
var istance;
$(function(){
istance = new object();
literal.call();
});
var literal = {
call: function() {
istance.foo();
}
}
function object(){
this.selector = $('div');
this.foo = function(){ this.selector.remove(); }
}

How to access a variable within a function

How do I access a variable that is defined within a function like this:
var functionVar = function(){
this.var = 1;
}
console.log(functionVar().var); //MH - obviously this doesn't work, but I'm looking for the command that will log that variable
You can access like this,
var functionVar = function(){
this.var = 1;
}
var o = new functionVar();
alert(o.var)​
a new will do the trick.
var functionVar = function(){
this.var = 1;
}
console.log(new functionVar().var);
Though not sure what you are trying to achieve by using this code.

javascript: namespace pollution

I am trying to submit my addon to the mozilla site but I am getting this damn warning:
The code (in mf_options.js) is pretty simple (and i think the problem is only between the "start storage" and "end storage":
// start Storage
var url = "http://mafiaafire.com";
var ios = Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var ssm = Components.classes["#mozilla.org/scriptsecuritymanager;1"]
.getService(Components.interfaces.nsIScriptSecurityManager);
var dsm = Components.classes["#mozilla.org/dom/storagemanager;1"]
.getService(Components.interfaces.nsIDOMStorageManager);
var uri = ios.newURI(url, "", null);
var principal = ssm.getCodebasePrincipal(uri);
var storage = dsm.getLocalStorageForPrincipal(principal, "");
// end Storage
function display_blocked_list1() {
var list = storage.getItem('domain_list_original');
if (list !== undefined) {
var strSingleLineText = list.replace(new RegExp( " ", "g" ), "<br>" );
var status = document.getElementById("div1");
status.innerHTML = strSingleLineText;
}
var list2 = storage.getItem('domain_list_redirect');
if (list2 !== undefined) {
// Strip out all line breaks.
var strSingleLineText2 = list2.replace(new RegExp( " ", "g" ), "<br>" );
var status2 = document.getElementById("div2");
status2.innerHTML = strSingleLineText2;
}
var list3 = storage.getItem('list_expiry_date');
if (list3 !== undefined) {
var dateArray = list3.split(",");
var future_date = new Date(dateArray[0],dateArray[1],dateArray[2]);
future_date.setDate(future_date.getDate()+2);
var status2 = document.getElementById("div3");
status2.innerHTML = future_date;
}
// ##################################################
}
You should definitely have a look at the link. However I also got this message and I'm fairly sure my code does not contain any (polluting) global variables.
But if this is exactly the code you use, then any function and variable you declare will be global. In its simplest case, wrap the code in an anonymous function call:
(function() {
// your code here
}());
If you need a global variable, because you have to call function from XUL elements, make sure you only have one. Create it inside the function call above with
window.YourPluginNamespace = {
// all functions or "subspaces" here
};
Wrap your code in a function envelope so your vars are local to that function body, and explicitly attach anything you want global to the global object.
(function (global) {
// your code here
global.myGlobalVar = myVar
}(this));
The problem is that you are using too many global variables, those defined outside of a function.
Imagine this scenario: my addon, Foo, uses a variable called sheep.
var sheep = 10;
Your addon, Bar, uses a variable also called sheep:
var sheep = 20;
When I go to access sheep, how can I be assured your addon hasn't modified it? This is the same reason addons use anonymous functions foo = function() {, because they are local.
To make you global variables more local, wrap your whole script in an anonymous function:
(function() {
var sheep = 10;
}());
Now, you can do whatever you wish with sheep and it will be local. Keep in mind, though, that you'd need some better scaffolding if you plan on making your application more complex. This method isn't completely bulletproof or scalable...

Categories

Resources