Creating objects
const circle = {
radius: 1,
location: {
x:1,
y:1
},
// method
draw: function(){
console.log('draw');
}
};
Factories and Constructors(return의 유무)
재사용성을 증가시키기위해 Factories 혹은 Constructor 함수를 사용할 수 있다
// Factory function
function createCircle(radius){
return {
radius,
draw: function(){
console.log('draw');
}
};
}
const circle = createCircle(1);
// Constructor Function
function Circle(radius){
this.radius = radius;
this.draw = function() {
console.log('draw');
}
}
}
Circle.call({}, 1) // 1st arg: target of this
Circle.apply({}, [1,2,3]);
const another = new Circle(1); // new 가 없다면 this가 window가리킴
// 1. new 키워드가 새로운 obj 생성 -> {}
// 2. this가 새 obj 가리킴(Circle)
// 3. circle 함수에서 리턴한다(new 키워드사용시 자동적으로 리턴, return 키워드 필요없음)
Primitives(copy by value) and Reference Types(copy by reference)
Working with Properties
dot notation, bracket notation
for in
Object.keys()
in OBJECT NAME(check existence of a property or method in ojbect)
Private Properties(abstraction)
function Circle(radius) {
this.radius = radius;
let defaultLocation = {x:0, y:0};
let computeOptimumLocation = function(factor) {
}
this.draw = function() {
computeOptimumLocation(0.1);
//defaultLocation
//this.radius
console.log('draw');
};
}
const circle = new Circle(1)
// circle. draw & radius
Getter and Setter
function Circle(radius) {
this.radius = radius;
let defaultLocation = {x:0, y:0};
this.getDefaultLocation = function() {
return defaultLocation;
};
this.draw = function() {
console.log('draw');
};
Object.defineProperty(this, 'defaultLocation', {
get: function() {
return defaultLocation;
},
set: function(value) {
if(!value.x || !value.y)
throw new Error('Invalid location');
defaultLocation = value;
}
});
}
const circle = new Circle(1)
circle.defaultLocation = 1;
circle.draw()
EXERCISE
function Stopwatch() {
let startTime, endtime, running, duration = 0;
this.start = function() {
if(running){
throw new Error('stopwatch has already started!')
running = 1;
startTime = new Date();
};
this.stop = function() {
if(running !== 0)
throw new Error('stopwatch is not started')
running = 0;
endTime = new Date();
const seconds = (endTime.getTime() - startTime.getTime())/1000;
duration += seconds
};
this.reset = function() {
startTime = null;
endTime = null;
running = 0;
duration = 0;
};
Object.defineProperty(this, 'duration', {
get: function(){
return duration
}
});
}
'코드스테이츠(Immersive) > 스프린트' 카테고리의 다른 글
n-queens 스프린트 진행 (0) | 2019.08.02 |
---|---|
프로토타입 (0) | 2019.07.29 |
상속 패턴 (0) | 2019.07.28 |
Data Structures2(Tree, B-Tree, Graph, Hash Table) (0) | 2019.07.24 |
Data Structures(Stack, Queue, Linked List) (0) | 2019.07.24 |