객체 실제로 사용하기
console.log("Math.PI", Math.PI);
console.log("Math.random()", Math.random());
console.log("Math.floor(3.9)", Math.floor(3.9));
// 객체에 소속된 함수 = 메소드
var MyMath = {
PI: Math.PI,
random: function(){
return Math.random();
},
floor: function(val) {
return Math.floor(val);
}
}
console.log(MyMath.PI);
console.log(MyMath.random());
console.log(MyMath.floor(3.9));
"this" 란?
메소드 내에서 메소드가 속한 객체를 참조 할 때 사용하는 키워드
var kim = {
name: 'kim',
first: 10,
second: 20,
sum: function(){
return this.first + this.second;
}
}
// this: 메소드 내 객체 지칭!
// 객체 이름이 바뀌어도 유연하게 대처 가능
console.log("kim.sum(kim.first, kim.second)", kim.sum());
// console.log("kim.sum(kim.first, kim.second)", kim.sum(kim.first, kim.second));
생성자(constructor)
/*
var kim = {
name: 'kim',
fisrt: 10,
second: 20,
third: 30,
sum: function() {
return this.fisrt + this.second + this.third;
}
}
var lee = {
name: 'kim',
fisrt: 10,
second: 10,
third: 10,
sum: function() {
return this.fisrt + this.second + this.third;
}
}
console.log(kim.sum());
console.log(lee.sum());
*/
var d1 = new Date('2022-2-13'); // 날짜 객체 d1 (생성자)
console.log('d1.getFullYear()', d1.getFullYear());
console.log('d1.getMonth()', d1.getMonth());
function Person(name, first, second, third) {
this.name = name;
this.fisrt = first;
this.second = second,
this.third = third,
this.sum = function() {
return this.fisrt + this.second + this.third;
}
}
// 생성자 함수: 객체를 찍어내는 공장.
// 인자를 바꾸면 객체를 계속 찍어 낼 수 있다.
// 중복 제거, 수정 용이
console.log(new Person());
var kim = new Person('kim', 10, 20 ,30);
var lee = new Person('lee', 10, 10, 10);
console.log(kim.sum());
console.log(lee.sum());
프로토타입(prototype)
function Person(name, first, second, third){
this.name=name;
this.first=first;
this.second=second;
}
// prototype 함수: 객체들이 공통으로 사용 -> 메모리 절약 필요
// 외부로 빼서 따로 만듦 -> 생성자.프로토타입
Person.prototype.sum = function(){
return 'prototype : '+(this.first+this.second);
}
var kim = new Person('kim', 10, 20);
// 이 객체의 sum 속성만 바꾸고 싶다면?
kim.sum = function(){
return 'this : '+(this.first+this.second);
}
var lee = new Person('lee', 10, 10);
console.log("kim.sum()", kim.sum());
console.log("lee.sum()", lee.sum());
생활코딩으로 독학하기!
prototype - JavaScript 객체 지향 프로그래밍
수업소개 JavaScript의 prototype이 필요한 이유와 prototype을 통해서 코드의 재사용성과 성능을 향상시키는 방법을 알려드립니다. 강의1 prototype이 필요한 이유를 소개합니다. 강의2 prototype을 이용
opentutorials.org
'Web > JavaScript' 카테고리의 다른 글
자바스크립트 기초 (0) | 2023.05.11 |
---|---|
생활코딩 JavaScript 객체지향 프로그래밍 (4) (0) | 2022.03.23 |
생활코딩 JavaScript 객체지향 프로그래밍 (3) (0) | 2022.03.06 |
생활코딩 JavaScript 객체지향 프로그래밍 (1) (0) | 2022.02.12 |
생활코딩 JavaScript OT (0) | 2021.04.09 |