How do I access one function's content in an IIFE? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have written some javascript code using the IIFE, here I have stored a variable x in a function item1 inside the IIFE hidden. Now I want to create another function, say item2 and I want to use the variable x inside this new function. And how exactly do I do this?
var hidden = (function () {
var item1 = function () {
x = 5;
}
})();

x can be a variable in your iife so it acts like a private variable while you only expose the closures item1 and item2.
Below is a simple example:
var hidden = (function(){
var x;
var item1 = function(){
x=5;
}
var item2 = function(){
return x;
}
return {
item1: item1,
item2: item2
}
})();
hidden.item1()
console.log("value of x", hidden.item2())

Related

Why do elements from html to js file go as objects [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
var toplama_islemi = (document.getElementById("toplama_islemi").style.display ="none");
var cıkarma_islemi = (document.getElementById("cıkarma_islemi").style.display ="none");
var carpma_islemi = (document.getElementById("carpma_islemi").style.display ="none");
var bolme_islemi = (document.getElementById("bolme_islemi").style.display ="none");
And why are there two equal signs here?
Those aren't comparisons. They're assignments. The styles are applied to the elements, and then the elements' style property values are assigned to variables.
Here's a demonstration.
setTimeout(function() {
var toplama_islemi = (document.getElementById("toplama_islemi").style.display = "none");
var cıkarma_islemi = (document.getElementById("cıkarma_islemi").style.display = "none");
var carpma_islemi = (document.getElementById("carpma_islemi").style.display = "none");
var bolme_islemi = (document.getElementById("bolme_islemi").style.display = "none");
console.log({toplama_islemi, cıkarma_islemi, carpma_islemi, bolme_islemi});
}, 2000);
<p>Wait for it...</p>
<div id="toplama_islemi">toplama_islemi</div>
<div id="cıkarma_islemi">cıkarma_islemi</div>
<div id="carpma_islemi">carpma_islemi</div>
<div id="bolme_islemi">bolme_islemi</div>
Everything is an object in JavaScript (except primitive values). If you don't want the style property values returned, do the steps separately:
var toplama_islemi = document.getElementById("toplama_islemi");
toplama.style.display = "none";
Now the element is assigned to the variable instead.

Can I refactor this code in any way in javascript? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
I have a 'render' function:
render: function(playerId){
this.getTotalPoints(playerId);
// and some other code after this;
}
This 'render' function may be executed with or without a playerId. This is the getTotalPoints function:
getTotalPoints: function(playerId){
if(playerId){
this.allplayers[playerId].totalPoints = this.calculatePoints(this.allplayers[playerId].cards);
}else{
this.allplayers.forEach(function(element, index){
element.totalPoints = this.calculatePoints(element.cards);
}.bind(this));
}
}
And the third function that actually calculates the points
calculatePoints: function(cards){
points = 0;
for( var i = 0; i < cards.length; i++){
points+=cards[i].points;
};
return points;
}
I am repeating myself in getTotalPoints, where I have a call to this.calculatePoints - one for a single player and then one for all the players, depending on whether the playerId is set or not.
Is there any chance I can avoid this and simplify the code?
I would do something like:
getTotalPoints: function(playerId){
var selected = playerId ? [this.allplayers[playerId]] : this.allplayers;
selected.forEach(function(element, index){
element.totalPoints = this.calculatePoints(element.cards);
}.bind(this));
}
However, since you're changing the state of the players, I would not call the function getTotalPoints, maybe computeTotalPoints?
I see two different functions: calculatePointsForPlayer and calculatePointsForPlayers. Second function will call first function.

Is it possible to have a Javascript variable to have two or more functions inside? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have the following Javascript code:
var Lab = {
minseat: function(){
var seat = 10;
return seat;
}
maxseat: function(){
var seat = 50;
return seat;
}
}
So, when I need to get the value, I simply call the following code:
console.log(" Min Seat: " + Lab.minseat());
console.log(" Max Seat: " + Lab.maxseat());
However, it seems it is not working. So, may I know if it is possible to have a Javascript variable to have two or more functions inside?
You forgot a comma after the first function:
var Lab = {
minseat: function(){
var seat = 10;
return seat;
},
maxseat: function(){
var seat = 50;
return seat;
}
}
How about a comma separating the keys in your object definition.
var Lab = {
minseat: function(){
var seat = 10;
return seat;
},
maxseat: function(){
var seat = 50;
return seat;
}
}
http://jsfiddle.net/V4Yje/

What happens in the execution context when this script is executed [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
When i execute the following script the alert statement is printing the function why is it so?
What happens in the execution context? Why the variable basicPattern's undefined value is not printing?
function basicPattern(){
var o = 5;
return o;
}
var basicPattern;
console.log(basicPattern);
function basicPattern(){
var o = 5;
return o;
}
var basicPattern;
console.log(basicPattern);
Evaluates same as this (IE bugs disregarded):
var basicPattern;
basicPattern = function basicPattern(){
var o = 5;
return o;
};
console.log(basicPattern);
Since basicPattern was already declared, declaring it again won't have any effect since declarations
are hoisted and merged. If you had assignment to 5 it would go like this:
var basicPattern;
basicPattern = function basicPattern(){
var o = 5;
return o;
};
basicPattern = 5;
console.log(basicPattern);
Read more about hoisting: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

What is the best way to call a function that receives single objects as argument when you have collections instead? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Sometimes you have a function that will work for flat arguments. For example:
send(player,message)
But what if, instead, you have collections of players / messages?
message = ['Welcome!','Check our site for events.']
players = [Player1,Player2,Player3]
Writting for-loops will reduce readability and won't work if you don't know statically if your argument is a collection or object. Rewritting the function is sometimes not viable or too laborous and promotes duplicate code. What is a simplier solution?
You can write a decorator that will transform your function into a function that will take the cartesian product of it's own arguments and call the original function on it.
function send(player,message) {
console.log('To ',player,': ',message);
}
cartesian(send)(['Player1','Player2','Player3'],['Welcome!','Check our site.']);
//Output:
//To Player1 : Welcome!
//To Player1 : Check our site.
//To Player2 : Welcome!
//To Player2 : Check our site.
//To Player3 : Welcome!
//To Player3 : Check our site.
This implements the decorator ("cartesian") on Javascript:
function cartesian_product(arr){
//cartesian_product( [[1,2],[3,4]] ) = [[1,3],[1,3],[2,3],[2,4]]
function partial_product(arr,i){
//partial_product([[1,2],3],0) = [[1,3],[2,3]]
var result = []
for (j=0; j<arr[i].length; ++j){
arr_changed = arr.slice();
arr_changed.splice(i,1,arr[i][j]);
result.push(arr_changed);
};
return result;
};
var result = [arr.slice()];
for (var x=0; x<arr.length; ++x){
for (var y=0; y<result.length; ++y){
if (result[y][x] instanceof Array) {
result.splice.apply(result,[y,1].concat(partial_product(result[y],x)));
}
}
}
return result;
};
function cartesian(func){
//cartesian(func)([1,2],[3,4]) = [func([1,3]),func([1,4]),func([2,3]),func([2,4])]
_this = this;
return function(){
var args_list = cartesian_product(Array.prototype.slice.call(arguments));
var return_values = []
for (var i=0; i<args_list.length; ++i){
return_values.push(func.apply(_this,args_list[i]))
}
return return_values;
}
}

Categories

Resources