본문 바로가기

Udemy/JavaScript:Understanding the weird part

closure and keyword 'this'

'CLOSURE'

외부 함수의 변수에 접근할 수 있는 내부 함수

Closure only exists when an inner function makes use of variables defined from an outer function that has returned.

Closure does not exist if you do not return an inner function and if that inner function does not make use of variables returned by an outer function.

JavaScript will only remember values that are being used inside of the inner function, not all variables defined in the outer function.

We can use closures to create private variables and write better code that isolates our logic and application.

function htmlMaker(tag) {
	let startTag = '<' + tag + '>';
    	let endTag = '</' + tag + '>';
    return function(content) {
    	return startTag + content + endTag;
        }
    }
    
let divMaker = htmlMaker('div');
divMaker('code');	//	<div>code</div>
divMaker('states'); //	<div>states</div>

 

클로저 모듈 패턴

function makeCounter() {
	let privateCounter = 0;
    
    return {
    	increment: function() {
        	privateCounter++;
            },
        decrement: function() {
        	privateCounter--;
           	},
        getValue: function() {
        	return privaeCounter;
            }
         }
     }

 

'this'

	//class
function Car(brand, name, color){
    this.brand = brand;		// avante === this
    this.name = name;
    this.color = color;
}

let avante = new Car('htundai', 'avante', 'black');
	instance

 

Bind

 

'Udemy > JavaScript:Understanding the weird part' 카테고리의 다른 글

The Scope Chain  (0) 2019.04.15
The 'new' keyword  (0) 2019.03.08
Object-Oriented Javascript and Prototypal Inheritance  (0) 2019.03.04
Objects and Functions  (0) 2019.02.24
Types and Operators  (0) 2019.02.23