How to access array/object inside function in javascript ? - javascript

Hello I have array outside function like below :
var daily = [];
daily["data"]=[];
daily["data"].push('hello');
function demo()
{
console.log(daily); // not working here
}
How to declare this object as global in Javascript ?

It could be because your function is being hoisted. Try this instead for your function.
var demo = function(){
console.log(daily);
}
You might also considering just passing that daily variable into your function like so,
var demo = function(d){
console.log(d);
}
then when you want to call it.
demo(daily);

Related

How to get function self reference from within that function?

is there any way to get function reference when i'm inside function?
var arrayOfFunction = [ myFunction ];
arrayOfFunction[0]();
function myFunction() {
removeFromArray( thisFunctionReference ) // how to get function self reference here?
};
function removeFromArray(functionRef) {
index = arrayOfFunction.indexOf(functionRef);
if (index > -1) {
arrayOfFunction.splice(index, 1);
}
}
In JavaScript, functions are first class members and thus behave like any other object. You can just refer to it by name like this:
myFunction.property = 5;
function myFunction() {
console.log(myFunction.property) //logs 5
console.log(myFunction) // logs the function
};
myFunction();
You can do following as well
removeFromArray(arguments.callee);
Whether you should do that or not will depend on whether you are planning to use "strict" mode in your app. More info in documentation.

javascript get inner object from function

I have a function in javascript
var fn = function(){
var obj = {result: true};
return obj.result;
};
I have access to the function, but I need to get the inner obj. Is there a way to do that?
EDIT: Thanks to the answers below, I have managed to come up with a solution.
https://stackoverflow.com/users/1447675/nina-scholz 's answer was the closest, so I marked it as the solution.
var f2 = function fn(){
fn.obj = {result: true};
return fn.obj.result;
};
A client of this function can use it like the following :-
var myFunction = f2;
The function must be called though, to access the inner variables
myFunction();
After that one can do the following.
console.log(myfunction.obj);
This seems to be working. I would, however like to know if this is a good practice.
You cannot access the inner object outside of the scope of the function.
you can access obj when you make it public.
function fn() {
fn.obj = { result: true };
return fn.obj.result;
}
console.log(fn());
console.log(fn.obj.result);

Assigning a function to a variable in JavaScript

function abc(){
//multiple variables and functions
a:function(){alert("a")};
}
function test(){
var k=abc();
k.a();
}
In the above case, I have a huge function abc() to be assigned to a variable. I want to call the member functions that are visible, like a() from the variable. Is this possible to implement and please give me a sample code if so.
When you include the parenthesis after your function, you're assigning the result of the function to your variable.
If you want to assign the function itself, just omit the parenthesis:
var k = abc;
k.a();
EDIT
Per #Kuba Wyrostek's answer, and #Pointy's comment, that a() function won't be properly exposed.
You'll need to take a look at the Module Pattern. What you need to do is to assign a function to a variable, and have that function return the functions that you want to be able to use outside of that function. This helps with encapsulation.
It's a little hard to tell from your code in the comment exactly what is the user-generated code, but I'll do my best.
var abc = (function () {
var grabApi,
initialize;
// Just an example of how to assign an existing function
// to a property that will be exposed.
grabApi = SCORM2004_GrabAPI();
// This is an example of how to have a property that will be
// exposed be a custom function passing a parameter.
initialize = function(initString) {
return SCORM2004_GrabAPI().Initialize(initString);
};
return {
getApi: grabApi,
init: initialize
}
}());
You can then use this abc object like this throughout your code. Again, this is trying to give an example of how to do what I think you're trying to do based on your comment.
// Assign the SCORM2004_GrabAPI function to a variable.
var SCORM2004_objAPI = abc.getApi();
// Call the Initialize function with an empty string.
abc.init("");
Hmmm… contrary to #krillgar's answer, I believe you were expecting your abc() to return new object. Something like this:
function abc(){
var privateVar;
return {
//multiple variables and functions
a:function(){alert("a")}
}
}
function test(){
var k=abc();
k.a();
}
You should make it an object. In this way you can access its property a.
var abc ={
a:function(){alert("a")}
}
function test(){
var k=abc;//Ofcrse remove the parenthesis
k.a();
}
test();

Access Instance variable in Javascript

I have a simple function, I am trying to access the instance variable. But it's giving me some error. How can I access instance variable in Javascript ? I tried below method, but not working
function Test(){
var a=10;
}
var test=new Test();
test.a=20;
For some reason I don't want to go with the following way:
var Test={
a:''
}
You declared a as a variable local to that function, so there is no way to access it outside (as you currently have it)
If you want a to be an instance variable attach it to the object
function Test(){
this.a=10;
}
var test=new Test();
test.a=20;
Change it to this :
function Test(){
this.a=10;
}
Here a good documentation on the subject : Introduction to Object-Oriented JavaScript
Existing answers tell you how to do it by making a a public property. If you really need a private variable, use the following code. The main reason you would use this instead of a public property is to prevent callers from setting a to invalid values.
function Test() {
var a = 10;
this.setA = function(val) {
a = val;
};
this.getA = function(val) {
return a;
};
}
var t = new Test();
t.setA(80);
t.getA(); // 80

Passing local variables from a function out to become global variables

I've spent the last two hours trying to figure out how to do this but nothing is working. Here is a short sample of some of my code. I want to get arrtime and several other similar variables out of the function so I can use them globally. Any ideas? Nothing too complicated please, I'm no expert (obviously).
function showTest(str) {
........
var arrayvals = JSON.parse(xmlhttp.responseText);
var arrtime= (arrayvals[0]);
}
var testvar=arrtime;
document.getElementById("testing").innerHTML=testvar;
The clean way to do this is using js-object notation:
function showTest(str) {
//other code
return {arr: arrayvals, tm: arrtime};
}
var func_result = showTest("blah-blah");
var testvar =func_result.tm;
var testvar2=func_result.arr;
But it's generally a bad idea to have global vars. Why do you need it?
Update sample code with global object
globals = {};
function q(){
globals['a'] = 123;
globals[123] = 'qweqwe';
}
function w(){
alert(globals.a);
//alert(globals.123); //will not work
alert(globals[123]); //that's OK.
}
q();
w();
You can declare the variables outside of the function.
var arrtime, arrayvals;
function showTest(str) {
arrayvals = JSON.parse(xmlhttp.responseText);
arrtime= (arrayvals[0]);
}
var testvar=arrtime;
alert (testvar);
var testvar;
function showTest(str) {
........
var arrayvals = JSON.parse(xmlhttp.responseText);
var arrtime= (arrayvals[0]);
testvar = arrtime;
}
alert (testvar);
The global is to be declared outside of the score of the function but assigned inside the scope of the function.
You simply have to omit var which indicates a variable that is only accessible from the function scope.

Categories

Resources