¡GoConqr estrena diseño! Cuéntanos qué te parece.

Apuntes

Javascript

Deepika Mohan Inglés 2 páginas

Contenido del apunte (2)

Página 1

Closure

Example of closure:

function createCounter() {

let counter = 0

const myFunction = function() {

counter = counter + 1

return counter

}

return myFunction

}

const increment = createCounter()

const c1 = increment()

const c2 = increment()

const c3 = increment()

console.log('example increment', c1, c2, c3)

Output -> example increment 1 2 3

BEST CLOSURE EXAMPLE

HTML

Click me!

You clicked me

number of times

JS

var test = (function(){

var count = 0;

return function(){

++count;

document.getElementById('event').innerHTML = count;

}

})();

ANOTHER CONCEPT OF CLOSURE

When you return an inner function from a function, that returned function will not be called when you try to call the outer function. You must first save the invocation of the outer function in a separate variable and then call the variable as a function. Consider this example:

function greet() {

name = 'Hammad';

return function () {

console.log('Hi ' + name);

}

}

greet(); // nothing happens, no errors

// the returned function from greet() gets saved in greetLetter

greetLetter = greet();

// calling greetLetter calls the returned function from the greet() function

greetLetter(); // logs 'Hi Hammad'

The key thing to note here is that greetLetter function can access the name variable of the greet function even after it has been returned. One way to call the returned function from the greet function without variable assignment is by using parentheses () two times ()() like this:

greet()(); // logs 'Hi Hammad'

Página 2

IIFE

A function declaration is the "normal" way of creating a named function.

// Named function declaration

function myFunction () { /* logic here */ }

On the other hand, if you are assigning a function to a variable or property, you are dealing with a function expression.

// Assignment of a function expression to a variable

var myFunction = function () { /* logic here */ };

// Assignment of a function expression to a property

var myObj = {

myFunction: function () { /* logic here */ }

};

The primary reason to use an IIFE is to obtain data privacy. Because JavaScript's var scopes variables to their containing function, any variables declared within the IIFE cannot be accessed by the outside world.

(function () {

var foo = "bar";

// Outputs: "bar"

console.log(foo);

})();

// ReferenceError: foo is not defined

console.log(foo);

Of course, you could explicitly name and then invoke a function to achieve the same ends.

function myImmediateFunction () {

var foo = "bar";

// Outputs: "bar"

console.log(foo);

}

myImmediateFunction();

// ReferenceError: foo is not defined

console.log(foo);

However, this approach has a few downsides. First, it unnecessarily takes up a name in the global namespace, increasing the possibility of name collisions. Second, the intentions of this code aren't as self-documenting as an IIFE. And third, because it is named and isn't self-documenting it might accidentally be invoked more than once.

It is worth pointing out that you can easily pass arguments into the IIFE as well.

var foo = "foo";

(function (innerFoo) {

// Outputs: "foo"

console.log(innerFoo);

})(foo);

//////////////////////////////////////////////////////////////////////////////////////////////

(function () {

// private scope

})();

The parenthesis at the end of the function tells the interpreter to execute it as soon as it reads it without invocation. We can add functions and variables in it and they will not accessible outside.

But if we want to access them outside, then use the Module Pattern:

var Module = (function() {

function privateMethod() {

// do something

}

return {

publicMethod: function() {

// can call privateMethod();

}

};

})();

The return statement of the Module contains our public functions. The private functions are just those that are not returned. Not returning functions makes them inaccessible outside of the Module namespace. But our public functions can access our private functions.

Información

Descripción
Apunte sobre Javascript, creado por Deepika Mohan el 13/05/2018.
Creado por
Deepika Mohan
Visitas
0
Valoración

Escríbenos

¿Sobre qué es tu mensaje?

¿Qué te parece el nuevo diseño?

¿Te gusta?