closures

need more explanation on w3schools javascript closure example

被刻印的时光 ゝ 提交于 2019-12-02 01:12:18
I'm trying to understand closures and am looking at the W3Schools javascript tutorial. This is one example they give by making a counter. <body> <p>Counting with a local variable.</p> <button type="button" onclick="myFunction()">Count!</button> <p id="demo">0</p> <script> var add = (function () { var counter = 0; return function () {return counter += 1;} })(); function myFunction(){ document.getElementById("demo").innerHTML = add(); } </script> </body> Example Explained The variable add is assigned the return value of a self-invoking function. The self-invoking function only runs once. It sets

Primitive variable does not live long enough

一曲冷凌霜 提交于 2019-12-02 01:08:10
问题 There is an error in this piece of code: let a: Vec<_> = (1..10).flat_map(|x| (1..x).map(|_| x)).collect(); The error message: error[E0597]: `x` does not live long enough --> src/main.rs:2:57 | 2 | let a: Vec<_> = (1..10).flat_map(|x| (1..x).map(|_| x)).collect(); | --- ^- - borrowed value needs to live until here | | || | | |borrowed value only lives until here | | borrowed value does not live long enough | capture occurs here But why? Is is a primitive type, i.e. it should be cloned anyway.

How to use struct self in member method closure

大兔子大兔子 提交于 2019-12-02 01:01:57
How can I call a method in closure? get_access_token method can set new access token based on self.get_base_url() : fn fetch_access_token(_base_url: &String) -> String { String::new() } fn get_env_url() -> String { String::new() } pub struct App { pub base_url: Option<String>, pub access_token: Option<String>, } impl App { pub fn new() -> App { App { base_url: None, access_token: None, } } pub fn get_base_url(&mut self) -> &String { self.base_url.get_or_insert_with(|| get_env_url()) } pub fn get_access_token(&mut self) -> &String { self.access_token .get_or_insert_with(|| fetch_access_token

Count functions calls with JavaScript

好久不见. 提交于 2019-12-02 00:48:20
For example: I have a lot of functions and use them many times. I need to count calls for each function. What is the best practice to make it? At first i thought i need closures, but I can't implement it in a right way. In the simplest case, you can decorate each function with a profiling wrapper: _calls = {} profile = function(fn) { return function() { _calls[fn.name] = (_calls[fn.name] || 0) + 1; return fn.apply(this, arguments); } } function foo() { bar() bar() } function bar() { } foo = profile(foo) bar = profile(bar) foo() foo() document.write("<pre>" + JSON.stringify(_calls,0,3)); For

Swift讲解专题八——闭包

梦想的初衷 提交于 2019-12-02 00:45:40
Swift讲解专题八——闭包 一、引言 Swift中的闭包是有一定功能的代码块,这十分类似于Objective-C中的block语法。Swift中的闭包语法风格十分简洁,其作用和函数的作用相似。 二、从一个系统函数看闭包 Swift标准函数库中提供了一个sort排序函数,对于已经元素类型的数组,调用sort函数会进行重新排序并返回新的排序后的数组。这个sort函数可以接收一个返回值为Bool类型的闭包,来确定第一个元素是否排在第二个元素前面。代码示例如下: var array = [3,21,5,2,64] func func1(param1:Int,param2:Int) -> Bool { return param1>param2 } //通过传入函数的方式 //array = [64,21,5,3,2] array = array.sort(func1) //通过闭包的方式 //array = [2,3,5,21,64] array = array.sort({(param:Int,param2:Int)->Bool in return param<param2 }) Swift语言有一个很显著的特点就是简洁,可以通过上下文推断出类型的情况一般开发都可以将类型的书写省略,这也是Swift语言设计的一个思路,由于闭包是作为函数的参数传入函数中的,因为函数参数的类型是确定

Passing an object property into a closure in PHP

只谈情不闲聊 提交于 2019-12-02 00:24:11
I am trying to pass an object property into a closure (that's within a method of that object), like so: class Entity extends ControllerBase { private $view; private $events; public function print($tid) { self::loadView($tid); self::loopView(); return (new StreamedResponse(function() use ($this->events){ ... } } } The $events property gets instantiated in the loopView() method. This seems like it should work to me, but I get this error: ParseError: syntax error, unexpected '->' (T_OBJECT_OPERATOR), expecting ',' or ')' in ... It seems to be saying it doesn't expect there to be an object

Moving from `prototype` and `new` to a closure-and-exposure pattern

感情迁移 提交于 2019-12-02 00:19:45
I have been re-factoring someone else's JavaScript code. BEFORE: function SomeObj(flag) { var _private = true; this.flag = (flag) ? true : false; this.version="1.1 (prototype)"; if (!this._someProperty) this._init(); // leading underscore hints at what should be a 'private' to me this.reset(); // assumes reset has been added... } SomeObj.prototype.reset = function() { /* perform some actions */ } /* UPDATE */ SomeObj.prototype.getPrivate = function() { return _private; // will return undefined } /* ...several other functions appended via `prototype`...*/ AFTER: var SomeObj = function (flag) {

Why Scala can serialize Function but not PartialFunction?

蹲街弑〆低调 提交于 2019-12-02 00:06:36
I have 2 functions (1 of them is partial) defined similarly under an object: val partialFn: scala.PartialFunction[String, Int] = new AbstractPartialFunction[String, Int] { override def isDefinedAt(v: String): Boolean = { counter += 1 if (v == "abc") true else false } override def applyOrElse[A1 <: String, B1 >: Int](v: A1, default: A1 => B1): B1 = { counter += 1 if (v == "abc") { v.length } else { default(v) } } } val optionFn: (String) => Option[Int] = { (v: String) => { counter += 1 if (v == "abc") { Some(v.length) } else { None } } } When they are both wrapped in an Option (definitely

JavaScript Closures and setTimeout

点点圈 提交于 2019-12-02 00:03:38
问题 Closures are something I still don't fully grasp in JS. I think this is a closure issue. I'm trying to create a progress bar. Every x seconds I want to increment the width of a DIV. Here's the part that is supposed to do that: for(i=0;i<=counter;i++){ setTimeout(function (){ myDiv.style.width = wIncrement+"px" timeIncrement++; wIncrement++; },timeIncrement*1000); } What I want to happen is every x seconds, increase the size of the bar. If course, that's not what's happening. I'm pretty sure

Groovy subclass called superclass method that accesses closure

一笑奈何 提交于 2019-12-01 23:46:48
I have a groovy superclass that looks like: class AGroovyClass { private String str = "hello" void printString(int nTimes) { nTimes.times { println str } } } and subclass class AGroovySubclass extends AGroovyClass { // some other subclass methods } My client code calls: new AGroovySubclass().printString(5) And this actually breaks because it says that that there is no such property "str" for AGroovySubclass I would have thought since the printString method is in AGroovyClass, it should have no problem accessing the "str" property, but clearly I am incorrect. If I wanted to keep "str" private,