JavaScript - object

예림·2023년 10월 18일
0
  • object (객체)
    :자바스크립트는 객체 기반 프로그래밍 언어이며, 원시 값을 제외한 나머지 값은 모두 객체이다
    객체는 0개 이상의 프로퍼티로 구성된 집합으로, 프로퍼티는 key와 value로 구성된다


properties 값이 함수일 경우 method라고 부른다

  • object literal
    : 자바스크립트에서 객체를 생성하는 가장 일반적인 방법이 객체 리터럴을 사용하는 것이다
    var 변수 = {
    key : value, // property
    ...
    key2 : function(){}, // method
    ...
    }
var sub = {
			subject : 'java',
			credit : 3,
			info : function(){
				return sub.subject + ' - ' + sub.credit + '학점';
			},
			info2 : function(){
				return this.subject + ' - ' + this.credit + '학점';
			}
		};
		console.log('과목평 : ' + sub.subject);
		console.log('학점 : '+ sub.credit);
		console.log(sub.info());
		console.log(sub.info2());
		console.log('');
  • delete()
    : 속성 삭제
delete sub.credit;
console.log('학점 : '+ sub.credit);
  • 속성추가
sub.credit = 4;
console.log('학점 : '+ sub.credit);
  • 속성 변경
sub.info2 = function(){
return '과목명 : ' + this.subject + ' / ' + this.credit + '학점';
}
console.log(sub.info2());
console.log('');
  • 객체 생성자 함수
    : new 연산자와 함께 호출하여 객체를 생성하는 함수를 생성자 함수(constructor)라 하며, 생성된 객체는 인스턴스(instance)라고 한다

object literal을 사용하면 하나의 객체만 생성하므로 같은 properties을 가지고 있는 객체가 여러개일 경우 비효율적이다 그래서 생성자 함수를 사용하게 되면 new를 통해 새로운 객체를 계속 생성할 수 있기 때문에 효율적이다

  • 생성자 함수의 인스턴스 생성 과정
    : new 연산자와 함께 객체(instance)가 생성 -> this바인딩
function Subject(name, credit){
this.name = name;
this.credit = credit;
this.info = function(){
return '과목명 : ' + this.name + ' / ' + this.credit + '학점';
};
}
var html = new Subject('html',3);
console.log('과목명 : '+ html.name);
console.log('과목명 : '+ html.credit);
console.log(html.info());
  • prototype
    : 객체의 메서드를 '생성사 함수'안에 정의하지 않고, 나중에 추가할 수 있다
    상속의 개념인데 프로토타입을 쓰는 이유는 동일한 메소드를 중복 소유하는 것은 메모리를 불필요하게 낭비하는 일로, 상속을 통해 불필요한 중복을 줄일 수 있다
function Rectangle(width, height){
this.width = width;
this.height = height;
}
Rectangle.prototype.area = function(){
return this.width * this.height;
}

var rectA = new Rectangle(3, 4);
console.log('넓이 : ' + rectA.area());
console.log('');
  • 객체의 propertis 열거
    : for .. in 문을 사용해서 속성을 전부 알 수 있다
    for(변수 in 객체명 {
    객체명[변수명]
    }
for(var p in rectA){
console.log(`${p} : ${rectA[p]}`);
}
  • class
    : JavaScript는 prototype 기반에 객체지향프로그램이다 그렇다면 js에서 class를 추가한 이유는 무엇일까
    class는 직관적으로 쉽게 코드를 읽을 수 있게 만들어 줄 뿐만 아니라, 작성하기도 쉽고 또 class 기반 언어에 익숙한 개발자가 더 빠르게 적응할 수 있기 때문이다
    constructor는 class에서 필요한 기초 정보를 세팅하는 곳이다 객체를 new로 생성할 때 가장먼저 자동으로 호출된다
class Subject {
constructor(name, credit){
this.name = name;
this.credit = credit;
}
get getName(){ return this.name; }

set setCredit(credit){
this.credit = credit;
}
info(){
return '과목명 :  ' + this.name + ' / ' + this.credit + '학점';
}
}

let js = new Subject('javascript', 3);
console.log('과목명 : ' + js.getName);
console.log(js.info());
console.log('');

js.setCredit =4;
console.log(js.info());

  • typeof
    : 선언된 변수가 어떤 타입인지 알려주는 함수
let a =10;
let b = new Number(10);
console.log('a 타입 : ' + typeof a);
console.log('b 타입 : ' + typeof b);
console.log('');
  • tofixed()
    : 소수점 자리 지정해주는 함수
let c = 123.45;
console.log('c : '  + c.toFixed(1));
console.log('');
  • isNaN()
    : 타입이 숫자 아닌것을 확인해주는 함수
    (참이 숫자가 아닌 것)
let d = '20' + '10';
console.log('d : '+ d);
if(isNaN(d)){
console.log('숫자가 아니에요 ~');
}else{
console.log('숫자 입니다 ...');
}
console.log('');

d = 'a';
console.log('d : '+ d);
if(isNaN(d)){
console.log('숫자가 아니에요 ~');
}else{
console.log('숫자 입니다 ...');
}
console.log('');


''안에 적어도 숫자라면 숫자임을 알려줌

  • parseInt()
    : 문자열을 파싱하여, 문자열의숫자 부분을 정수로 변환
  • 문자 + 숫자 => NaN , 숫자 + 문자 => 숫자만 출력, 띄어쓰기도 문자로 포함되서 띄어쓰기 뒤에 숫자는 잘림
  • parseFloat()
    : 문자열을 파싱하여, 문자열의숫자 부분을 실수로 변환

  • isInteger()
    : 정수인지 확인해주는 함수

  • Math.min()
    : 가장 작은 수를 반환하는 함수 ( '' or " "안에 적어도 숫자면 포함하여 찾아줌)

  • Math.max()
    : 가장 큰 수를 반환하는 함수 ( '' or " "안에 적어도 숫자면 포함하여 찾아줌)

  • Math.random()
    : 0.0 ~ 1.0 사이의 랜덤값을 생성

// 0~3까지 랜덤
let ra = Math.random();
console.log(Math.floor(ra * 4));
console.log('');

// 1~5까지 랜덤
for(let i=0; i<5; i++){
    let data = Math.random();
    console.log(Math.floor(data * 5)+ 1);
  • Math.round()
    : 소수점 첫째자리에서 반올림

  • Math.floor()
    : 소수점자리를 절삭

	console.log(Math.floor(12.34));
	console.log(Math.floor(12.56));
	console.log(Math.floor(-3.8));
	console.log(Math.floor(-3));
	console.log('');

  • 마이너스 값은 소수점이 있을 경우 무조건 반올림이 되어서 출력
  • Date
    : 날짜, 시간 정보를 가진 객체
	let now = new Date();
	console.log(now);
	console.log(now.toGMTString());
	console.log('');
	
	console.log(now.getFullYear() + '년');
	console.log(now.getMonth()	+ '월');
	console.log(now.getDate() + '일');
	console.log(now.getHours() + '시');
	console.log(now.getMinutes() + '분');
	console.log(now.getSeconds() + '초');
	console.log(now.getDay() + '요일'); // 일요일(0) ~ 토요일(6)
	console.log('');
	
	let date = new Date(2023, 10, 12);
	console.log(date);

profile
커피 잘 마시는 사람

0개의 댓글

관련 채용 정보