analogcoding

6/1 / Instantiation Patterns 2 본문

Be well coding/In Immersive

6/1 / Instantiation Patterns 2

be well 2019. 6. 3. 13:08

체크포인트

 

this / setTimeout

 

setTimeout 함수는 인자로 실행시킬 function 과 시간을 밀리세컨드 단위로 받는다.

 

var name = "Window";
var alice = {
  name: "Alice",
  sayHi: function() {
    alert(this.name + " says hi");
  }
};
var bob = { name: "Bob" };
setTimeout(alice.sayHi.call(bob), 1000);

위에 경우 return 값은 즉시 bob say hi 가 실행된다.

 

먼저 setTimeout 함수에서 첫번 째 인자로 받는 함수는 함수식을 받는다. 여기에 call , apply 로 함수를 실행하거나
즉시 실행되는 함수 () 의 경우 두번 째 인자로 받는 시간이 적용되기 전에 바로 실행되어서 시간 적용이 되지 않는다.

setTimeout 의 인자로 받는 함수의 실행이 인자에서 바로 된다면 시간이 적용되지 않음.

 

Instantiation Patterns 

 

1. functional

var Car = function() {
	var constructor = {};
	constructor.color = 'red'
	constructor.price = 100
    constructor.numbering = 1
	
    constructor.count = function(){
		this.numbering +=1;
	}
	return constructor;
}

함수를 하나 만들어서 내부 객체에 프로퍼티와 값을 준 뒤 변수에 함수 값을 대입해서 사용한다.

 

2. functional shared

var extend = function(to,from) {
	for(var key in from) {
		to[key] = from[key];
	}
};
 메소드와 틀이 되는 함수를 이어주는 extend 함수가 필요하다.

var carMethod = {};
carMethod.move = function() {
	this.position +=1;
};
메소드만 관리하는 객체를 생성해서 프로퍼티로 메소드를 생성

var Car = function(position) {
	var constructor = {
		position : position
	};
	extend(constructor,carMethod);
	return constructor;
};

functional 방식은 인스턴트마다 메소드를 할당하므로 메모리를 차지하지만 이건 메소드를 공유할 수 있어서 메모리 관리가 효율적이다.

 

3. prototypal

var carMethod = {};
carMethod.move = function() {
	this.position +=1;
};

var Car = function(position){
	var constructor = Object.create(carMethod);
	// carMethod 객체의 상속을 할 객체를 생성해서 constructor에 대입.
	constructor.position = position;
	return constructor
};

Object.create() 란?  특정 객체를 프로토타입으로 하는 객체를 생성한다. 이로써 carMethod의 속성을 상속한다.

 

4. pseudoclassical

var Car = function(position) {
	this.position = position;
};

Car.prototype.move = function(){
	this.position += 1;
};

var car1 = new Car(5)

원본에서 new 키워드를 사용해서 생성자를 만든다. 프로퍼티의 값을 인자로 받으면서 new Operator를 사용한다.

 

Comments