Questions tagged [closures]

1

votes
1

answer
27

Views

Identify if a function is a nested function

How can I identify whether or not a given function is: A closure function A nested function which isn't a closure Not a nested function I know I can say len(function.__closure__) > 0 but this would only answer whether or not this is a closure. What about a non-closure nested function? And is there a...
Aviv Cohn
1

votes
1

answer
263

Views

How to fix this closure syntax error: aka 'Optional<(Optional<UIActivityType>, Bool, Optional<Array<Any>>, Optional<Error>) -> ()>'

I am learning Ray Wenderlich. I met a closure syntax error. I want to know what do the Xcode tips mean? The Xcode reports as following: /Users/.../FlickrPhotosViewController.swift:107:54: Cannot assign value of type '() -> ()' to type 'UIActivityViewControllerCompletionWithItemsHandler?' (aka 'Optio...
dengApro
1

votes
3

answer
601

Views

iOS Swift Hw to acces data created in a completion handler closure — outside of the closure

I have some code that creates MapKit directions using the directions.calculateDirectionsWithCompletionHandler({(response, error) in method. The code works fine -- within the completion handler, but I can't figure out how to access the data outside the completion handler. I have defined the vars us...
user2984842
0

votes
0

answer
13

Views

textfield in closure swift

let creatorDB = Database.database().reference().child("A") creatorDB.queryLimited(toLast: 1).observe(.childAdded) { (snapshot) in let B = snapshot.value as! String print(B) let messageDB = Database.database().reference().child("\(B))/Messages/") let messageDictionary = ["Sender": Auth.auth().current...
J.Doe
0

votes
0

answer
18

Views

Local variables not valid in the callback, while some others are

I tried to write a small code to download many files (in this example: one .json and one .svg file) and I stumbled into some code I don't understand. I promise, next time I use a Promise, nonetheless, here is the code : var path_name = "some/path/to/go"; var item_name = "some_item_to_get"; var load_...
yota
1

votes
2

answer
57

Views

Global or Closure?

As per my understanding variable 'a' is a global variable. But when I check this in Chrome console, I find variable 'a' as a closure. Why? var a = 5; function abc() { var b = 4; return a*b; } console.dir(abc);
Vishal P
1

votes
2

answer
41

Views

JS: Why do you not return inner function with `function` word around it?

If I am making a factory function foo, why do I not return the inner function as function noiseMade() rather than just noiseMade() ? function foo() { let sound = "buzz" return { noiseMade() { return "I make" + sound } } }
John Nada
1

votes
2

answer
721

Views

Groovy equivalent for Scala implicit parameters - extended

This question extends my previous one Groovy equivalent for Scala implicit parameters Not sure if this is the right way to develop from a previous topic, but anyway.. I am looking for a way to express in groovy something like this: // scala object A { def doSomethingWith(implicit i:Int) = println ("...
Ghiro
1

votes
3

answer
210

Views

need help understanding JS code [closed]

Hi I am new to javascript and I cannot understand the following code: var createAdders = function () { var fns = []; for (var i = 1; i < 4; i++) { fns[i] = (function (n) { return i + n; }); } return fns; } var adders = createAdders(); adders[1](7); //11 ?? adders[2](7); //11 ?? adders[3](7); //11 ??...
Sahil
1

votes
1

answer
105

Views

Array of curried functions not acting properly

I'm relatively new to C#, so if the answer to this question is obvious I apologise. There's a portion of a program I am writing that stores an array of structs, and one of the elements of the struct is a curried function. The following is the portion of code causing the problem (minimised as far as...
JamesL
1

votes
4

answer
99

Views

How can I use closures with function pointers?

My goal is to use closures while still writing clean code. One thing I noticed is that somehow I always end up repeating myself because one of my anonymous functions is needed in more than one case. To this goal, I want to have these repeated functions stored in an object which I can later reuse. No...
Tiago Espinha
1

votes
1

answer
508

Views

Accessing private variables in a jQuery callback with the module pattern

The below executes without errors, but the DOM isn't updated. var Cart = function() { var $cart; function init() { $cart = $("#cart"); this.refresh(); } function refresh() { $.ajax({ // ... success: function(html) { $cart.html(html); // $cart seems to exist as JS object, but #cart doesn't get update...
randomguy
1

votes
2

answer
1.2k

Views

Coding an iterator to traverse binary tree

The question is, given a BST, find out whether there are two numbers that add up to a given number k. No extra memory should be used. Now if it were a sorted array, I could have simply kept two pointers, one at the beginning, one at the end. At each step I would compute the sum of the two numbers po...
SexyBeast
1

votes
3

answer
100

Views

referring to the current function without using its name/arguments.callee

I have done a fair amount of research but have not been able to find any answers, to what seems like a simple question: I want to associate a property with a function (to use as a static variable in this function), like so: function foo() { if (!foo.counter) { foo.counter = 1; } else { foo.counter++...
Himanshu P
1

votes
3

answer
520

Views

Best way to set up function in Javascript (likely via closure?)

I've got a web application that makes a call to a web service which returns some JSON representing an array of objects. Each object has some fields. Here's some example JSON to give an idea: { "data": [ { "id": "12345", "from": { "name": "John Doe", "id": "6789" }, "start_time": "2012-12-16T02:17:20...
BenjiFB
1

votes
2

answer
225

Views

javascript closure in for loop not working [duplicate]

Possible Duplicate: Javascript closure inside loops - simple practical example I'm having a problem with a closure in a phonegap application. I have a JSON object which contains instructions on how to create a form. This is roughly the code: for (var i in this.form.elements) { var element = this.fo...
brodney
1

votes
2

answer
488

Views

Self-modifying code in Ruby

I am concerned about writing self-modifying code in Ruby. And by self-modifying, I mean being able to write functions that take a code block as an input value, and output another code block based on this. (I am not asking about basics such as redefining methods at runtime.) What I might want to do i...
Boris Stitnicky
1

votes
1

answer
192

Views

Implementing scheme: closures and 'set!' conflict

Recently I met a conflict between set! and closures when implementing a scheme interpreter. The description of (set! var expr) is the following: (tspl) set! does not establish a new binding for var but rather alters the value of an existing binding. It first evaluates expr, then assigns var to the v...
Shou Ya
1

votes
2

answer
153

Views

Only the last value of For-of-Loop being passed to JQuery click function

I have the following For Of loop in CoffeeScript that loops through the properties of an object: for buildingFrame of buildingNames $("#bt-#{buildingFrame}").click () => @displayProperties(buildingFrame) It appears that only the last value of buildingFrame is passed to every call to @displayProperti...
Jamie Fearon
1

votes
2

answer
842

Views

Is this nodejs code a circular reference?

They are just a few lines from node.js official documents. client.on('data', function(data) { console.log(data.toString()); client.end(); }); I think client object has reference to the callback, the callback has a closure reference to client object. Is that correct? If yes, why is this encouraged?
Alvin Cao
1

votes
3

answer
62

Views

#<Closure> in output

I was writing a function to switch the last element of a list to the beginning: (define last-elem (lambda (l) (car (reverse l)))) (define all-but-last (lambda (l) (reverse (cdr (reverse l))))) (define (last-to-first x) (append (list last-elem x) (all-but-last x))) (last-to-first '(1 2 3 4 5 6)) It...
Chin
1

votes
2

answer
109

Views

Javascript object value not getting proper value

I'm writing a class project (we have to build a Frogger game using HTML5 canvas) and I have a a bunch of objects to help me out with different things like collision detection, movement, ect. The below object is one of those. Each view contains a Frame object which contains a function call hitTest th...
barndog
1

votes
3

answer
133

Views

Difference between named function expression, and using a variable reference?

from javascript.info: function makeArmy() { var shooters = [] for(var i=0; i
frrlod
1

votes
1

answer
450

Views

Can I find where a PHP anonymous function was defined?

Closures don't seem to be fully exposed to reflection. On inspection as an object, it doesn't seem to have anything useful: $foo = function ($a, $b) {}; $ref = new ReflectionObject($foo); var_dump($ref->getFileName()); // false You can get parameters of the anonymous function: $invoker = $ref->getMe...
Steve Clay
1

votes
1

answer
84

Views

Why does Access to Modified Closure Warning Disappear When Enumerable Method called with ()

Resharper's Access to Modified Closure warnings are usually quite helpful. I was just noticing that when I call the Any method inside of a for each loop, I'll get a warning if I don't use the open and close parenthesis. As soon as I add (), the error goes away. Does the error itself go away, or have...
KyleMit
1

votes
1

answer
627

Views

Why do we need blocks, function literals, closures in programming languages?

I program in Objective-C, I know a bit of Scala, Python and Javascript. While I'm comfortable with blocks in Obj-C, I would like to know what specific problem do they solve that I couldn't with the earlier versions of the language. Also - are blocks, closures, function literals, named functions, an...
Naz Mir
1

votes
1

answer
184

Views

Closures in programmatically generated Eloquent OR queries

I am trying to parse a query string into Eloquent that involves 'OR' statements. This is part of a much larger function that has other filters etc being applied, but I want to make an or_where group. My confusion comes with the closure.. and how to make sure the right values are passed through. If I...
Damon
1

votes
1

answer
45

Views

anonymous function calls with scoping issues [duplicate]

This question already has an answer here: passing index from for loop to ajax callback function (JavaScript) 3 answers I'm sure this has been asked before, but I don't know what to search for. So I want function to be called with a string that corresponds with the item clicked, but I want to simply...
tsjnsn
1

votes
4

answer
124

Views

Declare function twice for closure?

I've got something like this: // This executes once when the page loads. (function() { //under some conditions, it calls: myfunction(); function myFunction() { // defines function } }()); function thisIsCalledByAnOnClick() { // HERE I need to call myFunction() } I dont want myFunction() to be call...
1

votes
2

answer
753

Views

Best Practices in handling callbacks in node.js [closed]

I am creating a javascript class and in that I have this function which uses crypto module in node.js. I am not sure as to which would the best way to handle the callbacks. Take a look at the example and explain. Users.prototype.makeSalt = function(callback){ crypto.randomBytes(64, callback); }; OR...
Saransh Mohapatra
1

votes
3

answer
70

Views

js named function in parameter, can not access out of function

js named function in parameter, can not access out of function Because the 5th edition of ECMAScript forbids use of arguments.callee() in strict mode. mdn warning So I decided do not use the callee, instead , I use a named function The example in mdn function factorial (n) { return !(n > 1) ? 1 : f...
wener
1

votes
3

answer
45

Views

Access members within function/setting them from outside

I would really like to do this: var Html = function() { alert('internal: ' + this.val); }; Html.val = "x"; alert('external: ' + Html.val); Html(); but it doesn't work. why? how can I get the function code to see values set after its creation? - update - because my original post was not so clear in i...
ekkis
1

votes
3

answer
125

Views

Value of variable in nested function evaluate at definition time rather than at calltime [duplicate]

This question already has an answer here: JavaScript closure inside loops – simple practical example 39 answers Consider this code: for( var i = 1; i
NeverStopLearning
1

votes
2

answer
100

Views

Why is this closure not possible in python?

In python I am able to access the variable in outer function from the inner function and hence it forms a closure. However, I am not able to access a variable in outer class from the inner class like this, >>> class A: ... a=1 ... class B: ... b=1 ... def pr(self): ... print a,b ... >>>...
Never Back Down
1

votes
2

answer
305

Views

Retrieving response while preserving scope of “this” with jquery ajax

I used a closure to set this to _this inside the ajax success but now I have of course lost "response". Anybody know a way to retrieve the response data in this instance? var form = { name: 'great form', load:function() { $.ajax({ url: "get/data", type: "POST", success: function(_this){ c...
user240880
1

votes
3

answer
122

Views

Trying to iterate through an array and add a get function for each

I want to iterate through the style tags and write a GET function for each. The problem is the GET function is being written with a reference to 'styleTags[i]' instead of converting 'styleTags[i]' to the appropriate tag. var styleTags = ['cont', 'ecce']; for (var i = 0; i < styleTags.length; i++) {...
zach
1

votes
1

answer
91

Views

How to avoid deep nesting in nodejs tests?

would you mind sharing your best practices in testing nodejs? What is your experience in order to avoid deep nesting? Could not figure out how to refactor this code to closures when writing test. describe('ProcessRawData', function(){ describe('event that has been already handled', function(){ befor...
Edijs Petersons
1

votes
1

answer
142

Views

javascript closure rules and scope chain

The closure rule is: functions are executed using the scope chain that was in effect when they are defined. In the setTimeout callback function below, x is not yet in scope at the time of definition. Therefore, the program should print undefined, but it prints 7, why? what am I missing? var foo =...
user3124390
1

votes
2

answer
74

Views

how to fix the closure bug in my jQuery code

the page always alert "btn2" ,whenever I click btn1 or btn2. it's seem the problem caused the "click" closures.but I don't know how to fixed it. thanks in advance. untitled (function(){ $.fn.test = function(){ F.init.apply(this,arguments) }; var F ={ that:null, init:function(){ F.that = this; $(F....
Tim
1

votes
5

answer
276

Views

A deep understanding of javascript closures [duplicate]

This question already has an answer here: JavaScript closure inside loops – simple practical example 39 answers I'm trying to grasp this bit of code, I know it's a closure but I'm not getting the result I think I should get. This code returns me an [object MouseEvent], I can't understand why? I'm...
kevinius

View additional questions