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.
Related
Hi consider below code
let test={
a:function(){
console.log('Hi')
}
}
Is there a way to invoke property 'a' using a variable ?
This works ,
let test={
a:function(tmp){
console.log(tmp)
}
}
let functn='a';
test[functn]("hello");
but is there anyway to invoke the same like below code :
let test={
a:function(){
console.log('Hi')
}
}
let functn='a("hello")';
test.function;
The actual use case:
This is protractor system test related question,
I have a parent object with css locator [id=1] and the child elements has the locators [id=1]>div , [id=1]>span etc.
so currently parent element is stored as
let parent = element(by.css('[id=1']) ,
child as
let child1= element(by.css('[div]')
So to find all child elements of the parent element the function is :
element(by.css('[id=1']).element(by.css('[div]')
so instead of writing the locator again, i want to achieve:
parent.child1
This works ,
Yes, it does. Do that.
but is there anyway to invoke the same like below code :
No.
let functn=a("hello"); calls the function in the variable a and assigns its return value to functn.
Assuming that doesn't fail (because a isn't declared), then test.function looks at the value of the property named function (which has nothing to do with the variable function you just declared) on the object stored in test and does nothing with it.
Was able to make it work, i am converting everything to string and calling it using eval function:
let test={
a:function(tmp){
document.write(tmp)
}
}
let functn='a("hello")';
eval(Object.keys({test})[0]+'.'+functn)
If in case you are looking for a currying solution:
let test={
a:function(str){
return () => console.log(str)
}
}
let functn=test.a("hello");
functn();
At first you are passing a string which is not neccessary if you dont accept any parameters.
What you can do is using getters.
Documentation: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/get
let test={
get a (){
console.log('Hi')
}
}
So every time you are trying to access a it will be executed and so will print you 'Hi' in your console.
test.a;
There is and simpler form of the code
// Using Function Arrow
let test = (message => 'Hello World!')()
console.log(test)
// Using factory function
let data = function() {
return {
nome:'Jack'
}
}
console.log(data())
console.log(Object.values(data()))
You could change your approach to one without using eval by taking an array of key and parameter and a function which take the key and parameter and calls the function of the object.
let call = ([key, parameter]) => test[key](parameter),
test = {
a: function(tmp) { console.log(tmp); }
},
parameters = ['a', 'hello'];
call(parameters);
I try to update/export global variable (firstString) to use and validate it in 'Then' step.
How do I export it correctly? When I'm doing it this way, the firstString is undefined.
It works only when I export/import it inside steps. How can I update it globally and use it in 'Then' file?
helpers.js:
let firstString;
given.js:
let { firstString } = require('./helpers')
Given('I have first {string}', function (stringValue) {
return stringRequest(stringValue).then(response => {
firstString = response
});
});
module.exports = { firstString }
then.js:
firstString = require('./helpers').firstString
Then('blablabla {string}', function (stringType) {
console.log(firstString)
});
If I am correct in understanding what you want to do you are wanting to store data across steps. Todo that you will want to use the world instance that cucumber provides for you. You can access the world instance in steps via the this keyword.
So what you would do is
Given('I have first {string}', function (stringValue) {
return stringRequest(stringValue).then(response => {
this.firstString = response
});
});
Then('blablabla {string}', function (stringType) {
console.log(this.firstString)
});
For more information on the world instance check out https://github.com/cucumber/cucumber-js/blob/master/docs/support_files/world.md
I have created this:
var where = function(){
sym.getSymbol("Man").getPosition()
}
console.log(where);
if (where()<=0){
var playMan = sym.getSymbol("Man").play();
} else {
var playMan = sym.getSymbol("Man").playReverse();
}
This is for Edge Animate hence all the syms. I am trying to access the timeline of symbol Man, then if it is at 0 play it. But it isnt working and the reason, I think, is that I have an incomplete understanding of how a var works. In my mind I am giving the variable 'where' the value of the timeline position of symbol 'Man'. In reality the console is just telling me I have a function there, not the value of the answer. I have run into this before and feel if I can crack it I will be a much better human being.
So if anyone can explain in baby-language what I am misunderstanding I would be grateful.
Thanks
S
var where = function () { ... };
and
function where() { ... }
are essentially synonymous here. So, where is a function. You are calling that function here:
if (where()<=0)
However, the function does not return anything. You need to return the value from it, not just call sym.getSymbol("Man").getPosition() inside it.
That, or don't make it a function:
var where = sym.getSymbol("Man").getPosition();
if (where <= 0) ...
The value will only be checked and assigned once in this case, instead of updated every time you call where().
Try
var where = function()
{
return sym.getSymbol("Man").getPosition();
};
Your code wasn't returning anything.
var where = function() {
return sym.getSymbol("Man").getPosition()
}
console.log(where);
if(where()<=0) {
var playMan = sym.getSymbol("Man").play();
} else {
var playMan = sym.getSymbol("Man").playReverse();
}
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
}
I am new to Javascript. I am trying to understand where "this" is bound to using different examples. I am using console.log to print some values as shown below.
function FuncObject(value) {
this.answer = value;
this.get_answer = function () {
return this.answer;
}
};
var f = new FuncObject(42);
var fanswer = f.get_answer;
console.log(fanswer())
console.log prints "function" instead of "undefined". document.writeln seems to print "undefined" which is the right one because this is bound to the window object which does not have answer. Now printing function confuses me. Now I am wondering what i should be using for logging. I am unable to find an explanation for this.
thanks mohan
Just incase you didn't notice, there's a typo in your posted code of
this.get_answer = funcition ()
With that in mind, I'm not entirely sure of your experience level so let me cover all the bases.
function FuncObject(value) {
this.answer = value;
this.get_answer = function () {
return this.answer;
}
};
var f = new FuncObject(42);
var fanswer = f.get_answer;
console.log(fanswer())
You're setting fanswer = f.get_answer where f.get_answer is a function, so as such it sets fanswer to the function equivalent of this.get_answer.
If you want the return value of f.get_answer you need to call f.get_answer(), which returns 42.
With what you put, console.log(fanswer()) does print undefined as expected.
If you simply do console.log(fanswer) it records it as function, also as expected.
I'm not sure why you would receive function as you stated in your question, because I definitely do not, jsbin.