CSC/ECE 517 Fall 2011/ch3 4b js

From Expertiza_Wiki
Jump to navigation Jump to search

Closures

What is a Closure?

A closure is a block of code that can access the lexical environment of its definition. A closure has two properties:

- A closure can be passed as an object. - A closure recalls the values of all the variables that were in scope when the function was created and is able to access those variables when it is called even though they may no longer be in scope.

A closure can be thought of as essentially a function pointer that references a block of executable code and the variables from the scope it was created.

Closures in Ruby

Ruby supports closures through use of Procedures, or simply procs, and lambdas, which are Blocks.

Blocks

Procs and Lambdas

When creating a lambda or proc, the object holds a reference to the executable block and bindings for all the variables used by the block. In Ruby, we can create a Proc object explicitly in three different ways. 1. Using Proc.new 2. Using the proc method in the Kernel module 3. Using the lambda method in the Kernel module

Why use Closures?

Closures allow programmers to provide functionality with less code, since it stores state information.

Currying

Object-Oriented Programming in Ruby

Classes

Attributes

Inheritance

Access Control

Abstract Methods