How to access a variable within a function - javascript

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.

Related

Functions With Global Inputs Return NaN

Edit:
I wanted to be more specific about why I'm doing it this way. The code below is something I've been attempting to get working.
function newClass(self) {
this.invest;
this.interest;
function method1() {
return this.invest + this.interest;
}
}
var newC = new newClass();
newC.invest = prompt("Enter investment");
newC.interest = prompt("Enter interest");
alert(newC.method1());
End Of Edit:
I'm fairly new to the javascript language and can not figure out why my functions are always returning NaN. I have attempted many different fixes but nothing I have tried works. Below is an example.
function investment() {
var iniInvest;
var interest;
return iniInvest + interest;
}
investment.iniInvest = 10;
investment.interest = 20;
console.log(investment())
This returns a NaN. I have attempted creating classes and methods and attempted to parse the variables but they still all return NaN.
Unless the variables values are assigned to the var in the function
var iniInvest = 10;
or args are given
function investment(args1, args2) {
return args1 + args2;
}
console.log(investment(10, 20));
it will return NaN.
I appreciate the help.
You cannot access the variable inside functions like
investment.iniInvest = 10;
investment.interest = 20;
Since, you need that variables globally accessed so you can keep that variables outside the function and initialize them from anywhere in the code:
var iniInvest;
var interest;
function investment() {
return iniInvest + interest;
}
iniInvest = 10;
interest = 20;
console.log(investment())
The code investment.iniInvest = 10; is creating an iniInvest property on investment, not a local variable. This code does not modify the variable var iniInvest created within the function's scope.
function investment() {
return investment.iniInvest + investment.interest;
}
investment.iniInvest = 10;
investment.interest = 20;
console.log(investment())
This code achieves what you are asking, but this is not a good way to solve the problem.
The following is more likely what you are looking for:
function investment( iniInvest, interest) {
this.iniInvest = iniInvest;
this.interest = interest;
this.investment = function() {
return this.iniInvest + this.interest;
};
}
var inv = new investment( 10, 30 );
console.log( inv.investment() );
inv.iniInvest = 5;
inv.interest = 10;
console.log( inv.investment() );
As you are declaring iniInvest interest in function so you can not use that variable out of that function as they are out of scope. Make that variable global.
You can go through https://www.w3schools.com/js/js_scope.asp for scope of variables.
The problem is that when you declare a variable inside of a function, it exists only within that function, and is only local. Therefore, it can not be referenced from outside of the function.
In the example that you gave, you attempt to reference the variable investment.iniInvest and investment.interest, but those variables only exist within the local reference of the investment function, and are destroyed after the function ends, so you can not reference them. You're probably better off using args anyways.
You can try something like
var investment = function () {
this.iniInvest;
this.interest;
this.sum = function() {
return this.iniInvest + this.interest;
}
}
var i = new investment()
i.iniInvest = 10;
i.interest = 20;
console.log(i.sum());
Thanks everyone for all your answers! After reading everyones answer I was able to fix my syntax and resolve the problem.
This is my finished code.
function newClass() {
this.invest;
this.interest;
this.investment = function() {
return parseFloat(this.invest) + parseFloat(this.interest);
}
}
var newC = new newClass();
newC.invest = prompt("Enter investment");
newC.interest = prompt("Enter interest");
alert(newC.investment());
It returns the proper answer. Please do let me know if this code requires fixing.
Thanks Again!

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?

How do I wrap a javascript function with dynamic arguments?

I'd like to wrap some dynamically created javascript functions, similar to Daniel's accepted answer here:
How do I store javascript functions in a queue for them to be executed eventually
// Function wrapping code.
// fn - reference to function.
// context - what you want "this" to be.
// params - array of parameters to pass to function.
var wrapFunction = function(fn, context, params) {
return function() {
fn.apply(context, params);
};
}
The difference is I'd like the argument values to be dynamic at time of execution - is it possible to pass a reference to a variable in the arguments, which could be updated after it is wrapped?
Here's what I'd like to do:
// I have a function to be wrapped
var sayStuff = function(a,b) {
console.log(a);
console.log(b);
}
// Variables I'd like to pass
var randomNumberA = 0;
var randomNumberB = 0;
// Wrap the function
var fun = wrapFunction(sayStuff, this, [*reference randomNumberA*,*reference randomNumberB*]);
// variables get changed
randomNumberA = Math.random()*100;
randomNumberB = Math.random()*100;
// Execute the function using current values of randomNumberA & randomNumberB
fun();
If possible I'd like to do this without changing sayStuff, I have a lot of existing functions like this I'm hoping to wrap, which also get used outside of the wrapping, so ideally I'd like to not replace the arguments with an object.
Hope that makes sense, Thanks!
If the function and the variable will be created in the same scope you can just use that:
var randomNumber = 0;
var fun = function(){ alert(randomNumber); }
randomNumber = 10;
// Now this will alert 10, because when fun is executed
// JS looks in his scope to find what randomNumber is.
fun();
This happens because functions in javascript works as Closures, they carry their environment with them. See: https://en.wikipedia.org/wiki/Closure_(computer_programming)
So if randomNumber will be changed out of the scope where you bind that function, you need to use an object, this is because in javascript we don't have "pointers" or references to pass by. One way is using a object.
function giveMeAFunction(){
var params = { randomNumber: 0 }
var fun = function(){ alert(scope.randomNumber); }
return {fun: fun, scope: scope};
}
var paramsAndFun = giveMeAFunction()
// Now you can change the variables in the scope and call the function
paramsAndFun.params.randomNumber = 10;
paramsAndFun.fun(); // Will alert 10
// Now if you replace the entire params object it will not work
// This is because you will replacing it with a new object while
// The one that is referenced in the scope where fun was created is
// the old one.
paramsAndFun.params = { randomNumber: 15 };
paramsAndFun.fun(); // will still alert 10
Now let's get to binding part of the problem.
There is already Function.prototype.bind function to help you with that.
For example:
var sayStuff = function(opts) {
alert(otions.randomNumber);
}
var options = { randomNumber: 0 };
var fun = sayStuff.bind(this, options);
options.randomNumber = 10;
fun(); // Will print 10
There is a lot going on here. Sorry if I made everything confuse.
If the dynamic arguments are defined in the context argument, a solution can be based passing the name of the variables and then, at execution time, calculate its current value:
var wrapFunction = function(fn, context) {
var xArg = arguments;
return function() {
var argsArray = [];
for (var i = 2; i < xArg.length; i++) {
argsArray.push(context[xArg[i]]);
}
fn.apply(context, argsArray);
};
}
var sayStuff = function() {
for (var i = 0; i < arguments.length; i++) {
console.log('sayStuff func: ' + arguments[i]);
}
}
var randomNumber1 = 0;
var randomNumber2 = 0;
var fun = wrapFunction(sayStuff, this, 'randomNumber1', 'randomNumber2');
randomNumber1 = Math.random()*100;
randomNumber2 = Math.random()*100;
console.log('randomNumber1: ' + randomNumber1);
console.log('randomNumber2: ' + randomNumber2);
fun();

Global variable not defined from onclick?

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!

Calling one prototype method inside another in javascript

var Ob = function(){
}
Ob.prototype.add = function(){
inc()
}
Ob.prototype.inc = function(){
alert(' Inc called ');
}
window.onload = function(){
var o = new Ob();
o.add();
}
I would like to call something like this,how can i call, ofcourse i put inc as inner function to add I can do that but without having the inner function. how do i do that ?
It's easy:
Ob.prototype.add = function(){
this.inc()
}
Ob.prototype.inc = function(){
alert(' Inc called ');
}
When you create the instance of Ob properties from prototype are copied to the object. If you want to access the methods of instance from within its another method you could use this.

Categories

Resources