1. JS(JavaScript)는 Prototype 기반 언어(Prototype oriented language)이다.
2. 15_비구조화할당.js
// const 상수
const ironman = {
name: '토니 스타크'
, actor: '로다쥬'
, alias: '아이언맨'
};
const captain = {
name: '스티브로져스'
, actor : '크리스 에반스'
, alias: '캡틴 그분'
};
console.log(ironman);
console.log(captain);
// 객체를 매개변수로 받기
function print(hero){
let text = `${hero.alias}(${hero.name}) 배우: ${hero.actor}`;
console.log(text)
}
print(ironman);
print(captain);
// ES6 에 있는
// '비구조화할당 (destructuring assigment)문법'을 사용하면
// 객체변수.속성 <-- 좀더 편리하게 다룰수 있다.
// '비구조화할당 문법'
// 다른말로 '객체 구조 분해'
// 공식
// https://www.ecma-international.org/ecma-262/6.0/#sec-destructuring-assignment
// https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
// 추가 참조
// https://velog.io/@public_danuel/destructuring-assignment
// 비구조화 할당, 잘 사용하면 코드 깔끔해진다
function print(hero) {
// 객체 구조 분해
const{alias, name, actor} = hero;
// 어떤 (key) 값을 추출할지 명시
let text = `${alias}(${name}) 배우: ${actor}`;
console.log(text)
}
console.log('---------------------------------------------')
print(ironman);
print(captain);
// 함수 parameter 에도 비구조화 할당 가능!
// 훨씬 깔끔
function print2({alias, name, actor}) {
let text = `${alias}(${name}) 배우: ${actor}`;
console.log(text)
}
console.log('---------------------------------------------')
print2(ironman);
print2(captain);
// 꼭 함수 안에서만 사용할 수 있는 건 아니다..!!
const {name} = ironman;
console.log(name + " " + typeof name);
3. 16_객체안의함수_this.js
/* object 의 getter, setter
getter 함수: 특정 값을 조회할때마다
setter 함수: 특정 값을 설정할때마다
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/get
ES 5.1 에 최초 정의
https://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
ES 6 에서 계산된 프로퍼티 이름이 추가
https://www.ecma-international.org/ecma-262/6.0/#sec-method-definitions
JS 에서 매우 유용
*/
const numbers = {
a : 1
, b : 2
// getter 함수, 키워드명이 get임..!
, get sum(){
// get 키워드로 시작...!
console.log("sum 함수가 실행됩니다!");
// 반.드.시 무엇인가를 리턴해주어야 한다.
return this.a + this.b;
// return 이 빠지면 undefined 리턴.
}
}
// 그럼 getter는 어캐 호출할까?
// getter함수는 아래와 같이 '조회' 하려 할때
// 함수가 호출, 실행됩니다.
//console.log(numbers.sum()); // 에러 : TypeError: numbers.sum is not a function
// getter함수는 아래와 같이 호출해야 호출 가능함...!!
console.log(numbers.sum);
numbers.b = 5
console.log(numbers.sum);
// setter 함수
const dog = {
_name : "멍멍이"
// setter
// 키워드명이 set, set 키워드로 시작
, set name(value){
// 반드시 parameter 설정되어 있어야 함!
console.log("이름이 바뀝니다: " + value);
this._name = value;
}
}
console.log();
console.log(dog._name);
//dog.name('뽀삐'); // 에러 : TypeError: dog.name is not a function
// 함수처럼 하지말고 그냥 넣어라..!!
dog.name = '뽀삐'; // setter name() 호출
console.log(dog._name);
console.log();
4. 17_객체_getter_setter.js
/* object 의 getter, setter
getter 함수: 특정 값을 조회할때마다
setter 함수: 특정 값을 설정할때마다
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/get
ES 5.1 에 최초 정의
https://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
ES 6 에서 계산된 프로퍼티 이름이 추가
https://www.ecma-international.org/ecma-262/6.0/#sec-method-definitions
JS 에서 매우 유용
*/
const numbers = {
a : 1
, b : 2
// getter 함수, 키워드명이 get임..!
, get sum(){
// get 키워드로 시작...!
console.log("sum 함수가 실행됩니다!");
// 반.드.시 무엇인가를 리턴해주어야 한다.
return this.a + this.b;
// return 이 빠지면 undefined 리턴.
}
}
// 그럼 getter는 어캐 호출할까?
// getter함수는 아래와 같이 '조회' 하려 할때
// 함수가 호출, 실행됩니다.
//console.log(numbers.sum()); // 에러 : TypeError: numbers.sum is not a function
// getter함수는 아래와 같이 호출해야 호출 가능함...!!
console.log(numbers.sum);
numbers.b = 5
console.log(numbers.sum);
// setter 함수
const dog = {
_name : "멍멍이"
// setter
// 키워드명이 set, set 키워드로 시작
, set name(value){
// 반드시 parameter 설정되어 있어야 함!
console.log("이름이 바뀝니다: " + value);
this._name = value;
}
}
console.log();
console.log(dog._name);
//dog.name('뽀삐'); // 에러 : TypeError: dog.name is not a function
// 함수처럼 하지말고 그냥 넣어라..!!
dog.name = '뽀삐'; // setter name() 호출
console.log(dog._name);
console.log('---------------------------------------------------');
const numbers2 = {
_a : 1
, _b : 2
, sum : function() {
return this._a + this._b;
}
}
console.log(numbers2.sum());
numbers2._a = 10; numbers2._b = 20;
console.log(numbers2.sum());
console.log(numbers2.sum());
// 성능은 위의 코드보다는 아래의 코드가 좋음
// 함수를 어떻게 구성하느냐에 따라 성능의 차이가 있을 수 있음..!
const numbers3 = {
_a : 1
, _b : 2
, sum : 3
, get a() {return this._a}
, get b() {return this._b}
, set a(value) {
this._a = value;
this.sum = this._a + this._b;
}
,set b(value) {
this._b = value;
this.sum = this._a + this._b;
}
}
console.log('---------------------------------------------------');
console.log(numbers3.sum);
numbers3.a = 10; // setter 동작 + 연산 발생
numbers3.b = 20; // setter 동작 + 연산 발생
console.log(numbers3.sum); // 여러 번 조회해도 이미 연산된 결과 값만 보여줌, 재계산 안함
console.log(numbers3.sum);
5. 18_객체생성자.js
/*
프로토타입과 클래스
객체 생성자
프로토타입과 클래스에 대해서 알아보기 전에
우선 객체 생성자라는 것을 알아봅시다.
객체 생성자는 '함수'를 통해서
새로운 '객체'를 만들고
그 안에 '넣고 싶은 값' 혹은 '함수'들을
구현 할 수 있게 해줍니다.
*/
// Animal 이라는 객체 생성자
// (일반적으로 대문자로 시작하는 작명)
// 주로 생성자로 사용하는 경우 대문자로 시작
function Animal(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
// 공통적으로 사용하는 것은 프로토 타입으로 만드는 것이 일반적이다
this.say = function(){
console.log(this.sound);
}
}
let dog = new Animal('개', '멍멍이', '왈왈');
let cat = new Animal('고양이', '야옹이', '하악~');
dog.say();
cat.say();
/* 고찰..
새로운 객체가 new 생성될때마다
각 객체의 type, name, sound, say 가 '새로' 만들어진다.
음.. say 는 함수인데.. 계속 새로 만들어진다?
(비효율적이다, 함수는 동일한 내용인데...)
say 라는 함수를 바깥으로 꺼내어 재사용(?)해보기
바로 prototype 사용! ★
*/
console.log();
function Animal2(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
// Animal2 의 prototype 에 say() 를 만들고 동작시켜보기!
Animal2.prototype.say = function() {
console.log(this.sound);
}
bird = new Animal2('새', '짹짹이', '짹짹');
tiger = new Animal2('호랑이', '큰냥이', '어흥~');
bird.say();
tiger.say();
// prototype 에 정의해놓으면 모든 해당 객체가 곧 공통적으로 사용 가능하다.
// 왜 가능? Prototype Chain 때문에..!!
Animal2.prototype.sharedValue = 1;
console.log(bird.sharedValue);
console.log(tiger.sharedValue);
// 해당 부분은 자바와 혼동하면 안됨..!!
// bird에 sharedValue를 만들어서 10을 대입함!
bird.sharedValue = 10;
console.log(bird.sharedValue); // 출력 : 10
console.log(tiger.sharedValue); // 출력 : 1
6. 19_객체생성자상속.js
/*
객체 생성자 상속받기
예를 들어서 우리가 Cat 과 Dog 라는 새로운 객체 생성자를 만든다고 가정해봅시다.
그리고, 해당 객체 생성자들에서 Animal 의 기능을 재사용한다고 가정해봅시다.
그렇다면, 이렇게 구현 할 수 있습니다.
*/
//------------------------------------------
// 상속을 사용하지 않는 경우
{
console.log("상속을 사용하지 않는 경우");
function Dog(name, sound) {
this.type = "개";
this.name = name;
this.sound = sound;
}
function Cat(name, sound) {
this.type = "개";
this.name = name;
this.sound = sound;
}
Dog.prototype.say = function() {
console.log(this.sound);
};
Cat.prototype.say = function() {
console.log(this.sound);
};
let dog = new Dog("멍멍이", "멍멍");
let cat = new Cat("야옹이", "야옹");
dog.say();
cat.say();
// 위 코드를 보면 Dog, Cat 에 동일한 코드가
// 계속해서 중복으로 사용되고 있다..
// 이러한 경우, 상속이 필요하다
}
//------------------------------------------
// 상속을 사용하는 경우
console.log();
console.log("상속을 사용하는 경우");
function Animal(type, name, sound) {
console.log("Animal() 생성")
this.type = type;
this.name = name;
this.sound = sound;
}
Animal.prototype.say = function() {
console.log(this.sound);
}
Animal.prototype.sharedValue = 1;
// 생성자 상속
// Animal.call 을 호출!
// 여기서 첫번째 인자에는 this 를 넣어주어야 하고,
// 그 이후에는 Animal 객체 생성자 함수에서 필요로 하는 파라미터를 넣어주어야 합니다.
// 추가적으로 prototype 을 공유해야 하기 때문에
// 상속받은 객체 생성자 함수를 만들고 나서 prototype 값을 Animal.prototype 으로 설정해주었습니다.
// Dog() 와 Cat() 을 Animal() 이
// 가지고 있던것을 재사용함
function Dog(name, sound){
//console.log("Dog() 생성");
Animal.call(this, "개", name, sound);
// call(this, 상속하는 객체(부모) 생성자 매개변수들...)
// Dog의 추가되는 객체변수나 함수들은 아래에 추가하면 됨
this.weight = 34.5;
}
Dog.prototype = Animal.prototype;
function Cat(name, sound){
//console.log("Cat() 생성");
Animal.call(this, "고양이", name, sound);
}
Cat.prototype = Animal.prototype;
let dog = new Dog('멍멍이', '멍멍');
let cat = new Cat('야옹이', '야옹');
dog.say();
cat.say();
'웹_프론트_백엔드 > JAVA프레임윅기반_풀스택' 카테고리의 다른 글
2020.05.18 (0) | 2020.05.18 |
---|---|
프론트엔드 웹 페이지 제작하기(5.8 ~ 5.17) (0) | 2020.05.18 |
2020.05.14 (0) | 2020.05.14 |
2020.05.13 (0) | 2020.05.13 |
2020.05.12 (0) | 2020.05.12 |