[2022-08-22] TIL - 18일차
2022. 8. 22. 16:55ㆍGolfzon tech/TIL
😁 Today I Learned
- Object
- get,set
- static
- extends
- function
Object
<script>
console.log("hello objecgt...");
// [] : array
// {key : value, key : value} : object
let obj = {};
console.log(obj);
// object , JSON 객체 형식이네.
obj = {
name: "kim",
age: 33,
arr: [11, 22, 33],
vo: { id: "admin" },
fn: function () {} // 기능도 탑재가 가능하다.
};
console.log(obj);
obj = {};
console.log(obj);
obj["name"] = "lee";
console.log(obj);
console.log(obj["id"]);
obj["id"] = "admin";
console.log(obj["id"]);
// loop 에 돌릴 때는 얘를 쓴다.
console.log(obj["name"],obj["id"]);
console.log(obj.name,obj.id);
obj.arr = [11,22,33];
console.log(obj);
// 안에꺼를 출력하려면 이런 형태로 써야한다.
for (const i in obj.arr) {
console.log(obj.arr[i]);
}
// 정의가 안되어있으니까 에러
// obj.sleep();
// sleep 을 function 이용하여 정의
obj.sleep = function () {
console.log("sleep()...");
};
// 콜하기
obj.sleep();
// in 연산자 obj 안에 name이라는 Key 가 있니..?
console.log("name" in obj);
console.log("name2" in obj);
// key 삭제하기.
// delete obj.name;
// console.log(obj.name);
</script>
- [] : array. , {} : Object
- Object 는 JSON 객체형식과 비슷하다. (JSON 은 전부 String 타입이다. )
- for in 반복문에서 obj.[속성][key] 형태로 나타낸다.
- function 을 정의하고 싶을 때 obj.메서드이름 형식으로 정의하고 콜은 자바처럼 메서드이름(); 으로 콜한다.
- in 연산자를 사용하면 Object 안의 속성이 있는지 확인할 수 있다. (boolean 타입)
- key 를 삭제하고 싶을 때는 delete obj.속성
<script>
console.log("hello object2...");
// [] : array
// {key : value, key : value} : object
// array >> new Array(5);
// object >> new object(5);
let obj = new Object(5);
obj.num = 1;
obj.name = "kim";
obj.id = "admin";
obj.pw = 1234;
console.log(obj);
// 함수를 이용해서 생성하기. 첫글자가 대문자면 객체로 쓰려는게 목적이지 메서드가 목적이 아니야
function Studuent() {
console.log("Student()...");
}
// 함수를 콜한것이 되어버린다.
// let st = Studuent(); // 이거 콘솔 찍으면 undefined 뜸.
// new 를 붙인다면 원하는 것처럼 사용할 수 있다.
let st = new Studuent();
console.log(st);
// 이렇게 되면 Student에 키 밸류가 들어감.
st.num = 2;
st.id = "admin2";
st.pw = 1234;
console.log(st);
console.log("------------------------");
// 생성자는 명사형 첫글자 대문자 , 메서드는 동사형 첫글자 소문자.
function Person() {
console.log("Person...");
this.num = 1;
this.name = "choi";
this.age = 29;
}
let p = new Person();
console.log(p);
console.log("------------------------");
function Car(x,y) {
console.log("Car(x,y)...");
// 객체의 속성이다. price , model ㅇㅇ - this는 리턴 제어문을 대신한다.
this.price = x;
this.model = y;
}
let car = new Car();
console.log(car);
let car2 = new Car(1000,"audi");
console.log(car2);
// javascript 클래스에서 요로코롬 쓴다. 이건 옛날꺼다. 옛날에 쓰던거 ㅋ
// class ClassName {
// constructor();
// }
</script>
- new Object(5) 형태로 사용가능.
- function 첫글자 대문자 는 객체목적 , 소문자는 메서드 목적.
- class 클래스이름 형태로 사용한다.
<script>
console.log("hello object3...");
class Student{
kor = 99; // public ES2022
#tel = "010"; // # 붙으면 private ES2022
constructor(){
console.log("Student constructor...");
// this.name = "lee"; // 생성자에 속성을 넣을 수도 있네. ES6
// this._email = "aaa@aaa.com"; ES6
}
study(){
console.log("study....");
this.#yaja();
};
// private 은닉
#yaja(){
console.log("yaja()...");
};
firstTest(){
console.log("First Test....");
return 1;
};
}
let st = new Student();
st.num = 11;
console.log(st);
st.study();
console.log("-----------");
class Person{
age = 33;
#weight = 55.5;
constructor(){
console.log("Person constructor...");
}
sleep(){
console.log("Person sleep....");
this.#natJam();
};
// private
#natJam(){
console.log("nap sleep()...");
}
// 먹기
eat(food_name){
console.log("eat..." , food_name);
return [7,12,6]; // 배열 출력하려고 for문으로 돌리는구나.
};
}
let p = new Person();
p.name = "kim";
console.log(p.name,p.age);
p.sleep();
let arr_eatTime = p.eat("jae6bbokem"); // 한번만 콜 되기
for (const i in arr_eatTime) {
console.log(arr_eatTime[i]);
}
console.log("-----------");
class Car{
model = "audi"; // public
#driver_name = "lee"; // private
constructor(){
console.log("Car constructor...");
}
start(){
console.log("Car start....");
this.#turbo();
};
// private 은닉
#turbo(){
console.log("turbo...부아아아앙");
}
filloil(money){
console.log("filloil(money) ... ");
return String(money/1800) + "L";
}
}
let c = new Car();
c.price = 2000;
c.model = "volvo";
console.log(c);
c.start();
console.log(c.filloil(50000));
console.log("------------");
</script>
- 클래스안에 자바 전역변수처럼 속성을 넣을 수 있고 은닉하려면 변수 앞에 #을 넣으면 된다. 메서드도 마찬가지이다. 호출할 때도 역시 #을 붙여 콜한다.
- 생성자는 자바에서 클래스 이름을 가져온 것과 다르게 constructor() 를 사용한다.
- 속성 사용할때 1. 생성자에서 초기화해 사용해도 되고 밖에서 2. 객체를 생성한 후 사용해도 된다.
- 메서드에서 return 이 array 면 반복문으로 출력할 수 있다.
get , set
<script>
console.log("hello object4...");
// class 선언,
// constructor
// public & private field
// public & private method
// get set
class Student {
#name = "k";
#kor = 0;
#eng = 0;
#math = 0;
constructor(name = "noName", kor = 100, eng = 100, math = 100) {
console.log("Student constructor...");
this.#name = name;
this.#kor = kor;
this.#eng = eng;
this.#math = math;
}
// set
set name(name) {
this.#name = name;
}
// get
get name() {
return this.#name;
}
set kor(kor) {
this.#kor = kor;
}
get kor() {
return this.#kor;
}
set eng(eng) {
this.#eng = eng;
}
get eng() {
return this.#eng;
}
set math(math) {
this.#math = math;
}
get math() {
return this.#math;
}
}
let st = new Student();
console.log(st);
console.log("-----------");
class Person {
// 전역변수 무조건 써줘야함.
#num = 0;
#name = "noName";
#age = 0;
constructor(num, name, age) {
console.log("Person constructor...");
this.#num = num;
this.#name = name;
this.#age = age;
}
// set
set num(num) {
this.#num = num;
}
// get
get num() {
return this.#num;
}
set name(name) {
this.#name = name;
}
get name() {
return this.#name;
}
set age(age) {
this.#age = age;
}
get age() {
return this.#age;
}
}
let p = new Person(1, "yang", 33);
console.log(p);
console.log("-----------");
class Car {
#price = 0;
#model = "noModel";
#driver_name = "";
constructor(price, model, driver_name) {
console.log("Car constructor...");
this.#model = model;
this.#driver_name = driver_name;
}
// set
set price(price) {
this.#price = price;
}
// get
get price() {
return this.#price;
}
set model(model) {
this.#model = model;
}
get model() {
return this.#model;
}
set driver_name(price) {
this.#driver_name = driver_name;
}
get driver_name() {
return this.#driver_name;
}
}
let c = new Car();
// c.setPrice(1000);
c.price = 1000;
console.log(c.price);
// console.log(c.getPrice());
console.log("------------");
</script>
- getter , setter 를 자바처럼 get변수명, set변수명 처럼 써도 되지만 공백 한칸 넣고 <get 변수명> 형태로 사용한다.
static
<script>
console.log("hello object5...");
// class 선언,
// constructor
// public & private field
// public & private method
// get set
// static
class Student {
static name = "kim";
constructor() {
console.log("Student constructor...");
}
//static 메서드
static study() {
console.log("static study...");
}
//static 메서드
static #yaja() {
console.log("static yaja...");
}
}
let st = new Student();
console.log(st);
console.log(st.name); // undefined 남 . static이라서.
Student.name = "Lee"; // 할당
Student.study(); // 호출
console.log(Student.name); // 클래스자체를 가져와야 name을 뽑는다. 값 바뀜.
console.log(Student.study());
// console.log(Student.#yaja()); 접근을 못한다. 에러난다. #메서드는..
console.log("-----------");
class Person {
static age = 99;
constructor() {
console.log("Person constructor...");
}
// sleep()
static sleep() {
console.log("sleep()... ");
let p = new Person();
p.#natJam();
}
// natJam()
#natJam() {
console.log("#natJam()...");
}
}
let p = new Person();
console.log(p);
console.log(Person.age);
console.log(Person.sleep());
console.log("-----------");
class Car {
static price = 500;
model = "audi";
// static 초기화블럭
static{
Car.price = 50000;
this.model = "bmw";
}
constructor() {
console.log("Car constructor...");
// Car.price = 5000;
}
start(){
console.log("car start()...");
Car.turboOn(); // Car. 생략불가.
}
static turboOn(){
console.log("static turboOn...");
}
}
let c = new Car();
console.log(c);
console.log(Car.price);
console.log(c.model); // audi 가 나오지 static 블럭이 더 먼저 실행되어서 bmw -> audi 로 바뀜.
c.start();
console.log("------------");
</script>
- static 변수를 바깥에서 사용할때는 자바처럼 클래스명.변수명을 써야한다.
- static 메서드도 위와 같이 Student.study(); 로 호출한다.
- #이 붙어 은닉한 메서드는 밖에서 호출이 불가능하다.
상속 extends
<script>
console.log("hello object5...");
// class 선언,
// constructor
// public & private field
// public & private method
// get set
// static
// extends 단일 상속만 가능.
console.log("-----------");
class Person {
name = "kim";
constructor() {
console.log("Person constructor...");
}
sleep() {
console.log("sleep()... ");
}
}
class Student extends Person {
kor = 99;
constructor() {
super();
console.log("Student constructor...");
}
study() {
console.log("study...", this.name); // name 가져올 수 있네. this를 붙여서 쓰네.
}
} // end class
let st = new Student();
console.log(st);
st.sleep();
st.study();
// let p = new Person();
// console.log(p);
console.log("-----------");
class Car {
model = "noModel";
constructor(model) {
console.log("Car constructor...");
this.model = model;
}
start(){
console.log("car start()...");
}
}
class Bus extends Car{
stationCount = 20;
open(){
console.log("open()...");
}
}
let bus = new Bus("HD");
console.log(bus);
bus.start(); // 둘 다 호출 가능하네.
bus.open(); // 둘다 호출 가능하네
// let c = new Car("audi");
// console.log(c);
console.log("------------");
</script>
- 단일 상속만 가능하다.
Function
<script>
console.log("hello function");
// 1. arguements X return X
function sleep() {
console.log("sleep1()...");
}
sleep();
// 2. arguments X , return O
function sleep2() {
console.log("sleep2()...");
return 0; // 숫자, 문자열, 객체, 배열, 함수
}
sleep2();
console.log("return : ",sleep2()); // return 값
// 3. arguments O , return X
function sleep3(x) {
console.log("sleep3()....", x);
}
sleep3();
sleep3("kim");
// 4. arguments O , return O
function sleep4(x) { // x = 1 디폴트 값
console.log("sleep4()...",x);
// x = x || 1; 1이 디폴트값 ,,, NaN,NaN 이 뜨는데 디폴트값으로 괜찮아짐.
x ||= 1; // &&= , ??= 물음표(optional chaining)는 undefined 하고 null만 체크를 해준다.
// ?? = (?,?)
return [11*x,22*x,33*x];
}
sleep4();
sleep4(10); // 모든 리터럴 인자로 전달 가능.
console.log("return 1 : ",sleep4()); // return 값
console.log("return 2 : ",sleep4(10)); // return 값
</script>
- ||= , ??= 이 자바스크립트에서는 가능하다.
728x90
'Golfzon tech > TIL' 카테고리의 다른 글
[2022-08-25] TIL - 20일차 (0) | 2022.08.26 |
---|---|
[2022-08-24] TIL - 19일차 (2) | 2022.08.24 |
[2022-08-19] TIL - 17일차 (0) | 2022.08.20 |
[2022-08-18] TIL - 16일차 (0) | 2022.08.18 |
[2022-08-17] TIL - 15일차 (0) | 2022.08.17 |