I'm trying to use something like pointers in javascripts, this is what I have,
I have a set of values: {chart2:6, chart3:4, chart5:7}. For example I want to write a function where I can pass to it chart2 and it will return to me the value 6.
Thank you for your help.
this is the code im using now:
function pointers(copy,paste) {
obj[copy].value = paste;
}
function getPointer(copy) {
return obj[copy].value;
}
pointers(selectedIdsArray[s],semiId);
alert(selectedIdsArray[s]);
im calling the pointers function inside a loop and alerting them too in aloop,
but it giving the following error:
ReferenceError: obj is not defined
There are no C-style pointers in javascript. Your getPointer function needs to see the obj variable to be able to access it (like in the snippet below).
var obj = {
foo: { value: "foo" },
bar: { value: "bar" }
};
function pointers(copy, paste) {
obj[copy].value = paste;
}
function getPointer(copy) {
return obj[copy].value;
}
Related
CLOSURES IN JAVASCRIPT
Hi there,
I am facing some struggles with my javascript code, maybe you can help with the issue about closures.
this is my code:
function seatReservation(aSeat) {
let secret = aSeat;
return function (){
return secret;
}
};
class Reservations {
#aMailadress;
#mySeatList;
constructor(aMailadress){
this.#aMailadress = aMailadress;
this.#mySeatList = [];
}
addSeatReservation(aSeat){
this.#mySeatList.push(aSeat);
}
printReservations(){
this.#mySeatList.forEach(seat => {
console.log(seat);
});
}
};
// Test
const list = new Reservations('peter#mail.com');
list.addSeatReservation(new seatReservation('D3'));
list.addSeatReservation(new seatReservation('F6'));
list.printReservations();
the output in the console is:
[(Anonymous function)]
[(Anonymous function)]
Expected output:
D3
F6
Who can help?
Thanks
The new seatReservation('D3') creates a function which will, when called, return the secret passed to it. You could for example do: console.log(seat());. You call the function, thus retrieving the data from the closure.
Im building a chrome app and I am trying to add a function inside an object inside chrome.storage.local but when im doing it it does not appear if you try to get it (all the other things appear but not the function)
But if you try to do it on a normal object like
let a = {
b: function() {
return 'This is working'
}
};
then it works.
It wouldn't be a problem if I could just use eval but due to security on the chrome app it does not work.
What im trying to do is:
chrome.storage.local.set({
'obj': [{
example: 'hello',
fn: function() {
return 'This is not working'
}
}]
});
Then if you do
chrome.storage.local.get('obj', function(e) {
console.log(e.obj)
});
Then it will return with
Array (length 1): example: "hello"
and not the function,
Thanks.
Store arguments and the body like this
{function:{arguments:"a,b,c",body:"return a*b+c;"}}
Retrieve it and instantiate the function:
let f = new Function(function.arguments, function.body);
I'm new to JavaScript and NodeJS, and I need to solve this issue quickly.
connection(getSQL2)
.then((table)=> {
table.forEach(row=> {
let obj = {
countryid: row.IdPais,
country: row.NombrePais
};
data.push(obj);
});
});
console.log(obj);
When I try to display the object using console.log, I get undefined, which seems pretty obvious. But what would be an easy way to get it to display the Object 'obj' that was created above?
UPDATE: Just to clarify, console.log is used here only as an example. I need to access the object from outside that function however I can.
Thanks in advance!
Two things going on here.
1) You're using a promise and promises asynchronously resolve. Good rule of thumb is any code that ends with .then(...) is going to be a promise. What that means is that code underneath it can execute before the promise is finished and if it reads those values before the promise has finished resolving they will be read as undefined.
2) You use the let keyword to define your variable which means it will only be defined in the scope:
row => {
let obj = {
countryid: row.IdPais,
country: row.NombrePais
};
data.push(obj);
// Show the object where it is defined
console.log(obj);
}
you can create a global variable, and assign the value to that variable inside the that function.
Then, you will be able to access the variable obj outside the function also.
var temp;//declare a global variable here.
connection(getSQL2)
.then((table)=> {
table.forEach(row=> {
let obj = {
countryid: row.IdPais,
country: row.NombrePais
};
data.push(obj);
temp = obj;//assign value to global variable here
});
});
console.log(temp);//you can access the 'obj' using temp
Hope this helps you.
You need to do this:-
async database()
{
try {
const table= await connection(getSQL2);
if (table!== null)
{
table.forEach(row=> {
let obj = {
countryid: row.IdPais,
country: row.NombrePais
};
console.log('This will resolve the promise',obj);
}
else
{
//anything needed
}
}
catch (error)
{
// Error retrieving data
}
}
async and await are the keywords used in parallel. await keyword will not allow the control to go down until data is fetched.
I have an object:
var obj = { id: $('#f_view') };
I have a function:
function switchFrom(trigger) {
trigger.id.click(function() {
this.id.toggleClass('class');
});
};
When i run the function:
switchFrom(obj);
I get :
undefined is not a function (evaluating'this.id.toggleClass('class')')
When I refer to the element explicitly, the function works.
$('#f_view').toggleClass('class');
What Am i doing wrong? Thank you for your time.
You need to convert to a jQuery object by wrapping in $(...) like
function switchFrom(trigger) {
trigger.id.click(function() {
$(this).toggleClass('class');
});
}
This is because native javascript objects do not have access to jQuery methods
Hi guys I am writing some code using the object literal pattern, I have function that returns a value:
'currentLocation': function() {
var cL = 0;
return cL;
},
I then need to update the variable 'cL' from another function like this:
teamStatus.currentLocation() = teamStatus.currentLocation() + teamStatus.scrollDistance();
This part is part of another function - however I get an error back stating: invalid assignment left-hand side
I am guessing I can not update the variable in this way, could anyone suggest a better method or point me in the right direction.
Any help would be greatly appreciated.
Going to add more code to highlight what I am trying to do:
'currentLocation': function() {
var cL = 0;
return cL;
},
'increaseTable': function() {
if (teamStatus.currentLocation() <= teamStatus.teamStatusTableHeight() ) {
teamStatus.currentLocation = teamStatus.currentLocation() + teamStatus.scrollDistance();
$("#tableTrackActual").animate({scrollTop: (teamStatus.currentLocation)});
$("#tableMembers").animate({scrollTop: (teamStatus.currentLocation) });
//console.log(teamStatus.currentLocation());
teamStatus.buttonRevealer();
}
}
As you can see increaseTable should update the value of currentLocation - help this sheds more light on what I am trying to achieve.
You're writing teamStatus.currentLocation() =, which calls the function teamStatus.currentLocation and tries to assign to the return value. That isn't valid. You want just teamStatus.currentLocation = — no function call.
The variable inside your function is completely private to that function (and any functions defined within it). If you need to create a number of functions that share a set of private variables, you can do that with a closure. For instance:
var Thing = (function() {
var thingWideData;
function getData() {
return thingWideData;
}
function setData(newData) {
thingWideData = newData;
}
return {
getData: getData,
setData: setData
};
})();
What that does is create a Thing object which has getData and setData functions available for it, which get and set the completely private thingWideData variable contained by the anonymous closure. More about this pattern here and here, although the latter of those is more about private methods than private data.
What your code produces is:
0 = 0 + <some number>
Which variable do you want to update? cL? You are declaring it in the function, you cannot assign a value to it from outside. Depending on the rest of your code, you might be better off with getters and setters:
var object = {
_cL = 0,
get currentLocation() {
return this._cL;
},
set currentLocation(value) {
this._cL = value;
}
}
then you can do:
teamStatus.currentLocation = teamStatus.currentLocation + teamStatus.scrollDistance();
Update:
Regarding IE: If currentLocation should actually be just a number, it might be sufficient to just declare it as property:
var obj = {
currentLocation: 0
}