생성자함수, prototype, this (1), (2)
github커밋
OOP - Object Oriented Programming
)function Heroes(name, age) {
this.name = name;
this.age = age;
};
// 인스턴스 = new 함수이름(인자)
var superMan = new Heroes('Super Man', 30);
var blackWidow = new Heroes('Black Widow', 34);
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.fullName = function() {
console.log(this.firstName + " " + this.lastName);
}
}
var lee = new Person('Yesol', 'Lee');
var heo = new Person('JuYeon', 'Heo');
heo.fullName();
Person.prototype
객체가 함께 생성됨function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.fullName = function () {
console.log(this.firstName + " " +this.lastName);
}
// 인스턴스: 후손. 생성자 안 메서드 없어도 prototype의 메서드 사용 가능
var heo = new Person('JuYeon', 'Heo');
heo.fullName();
// 생성자 함수
function Person (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// 생성자 함수로 인스턴스 생성
var lee = new Person('Yesol', 'Lee');
console.log(lee.__proto__ === Person.prototype); // true
console.log(Person.prototype.__proto__ === Object.prototype); // true
console.log(lee.__proto__ === Object.prototype); // false 중간단계 뛰어넘기 불가능
console.log(Person.__proto__ == Function.prototype); // true
console.log(Function.prototype.__proto__ === Object.prototype); // true
// 인스턴스와 prototype은 모두 생성자함수로 만들어 진 객체
console.log(lee.constructor === Person); // true
console.log(Person.prototype.constructor === Person);
function a () {
console.log(this);
function b () {
console.log(this);
}
b(); // this = window
};
a(); // this = window
var btn_prev = document.querySelector('.btn-prev');
btn_prev.addEventListener('click', function() {
console.log(this); // this = btn_prev
});
var obj = {
age: 54,
sum: function () {
console.log(this.age); // this = obj
function c () {
console.log(this); // 중첩함수라서 this = window
}
c();
}
};
obj.sum();
var obj = {
age: 54,
sum: function () {
console.log(this.age);
var that = this;
function c () {
console.log(that);
}
c(); // 중첩함수라서 this = window
}
};
obj.sum();
var arr = [];
var i = 0;
// 이미지 정보 객체 생성자 함수
function NatureImage(name, img, txt) {
this.name = name;
this.img = img;
this.txt = txt;
}
// 생성자 함수로 이미지 인스턴스 만들어 배열에 삽입
function createNatureImage (name, img, txt) {
var fullImg = `img/img-${img}.jpg`;
var natureImage = new NatureImage(name, fullImg, txt);
arr.push(natureImage);
};
createNatureImage('nature 1 name', 1 , 'nature 1 description');
createNatureImage('nature 2 name', 2 , 'nature 2 description');
...
var arr = [10, 20, 30];
var index = 0; // 기준점
function loop() {
var current = index % arr.length; // 0 % 3 = 0
console.log(arr[current]);
index++;
setTimeout(function() {
loop()
}, 2000);
}
loop();
var words = ['엔드게임', '인피니티 워', '에이지 오브 울트론'];
var txtElement = document.getElementById('txt');
function TypeWriter(txtElement, words) {
this.txtElement = txtElement; // html 태그
this.words = words; // 단어 리스트
this.txt = ""; // 출력할 텍스트
this.wordIndex = 0; // 리스트에서 가져올 단어 인덱스
this.isDeleting = false; // 현재 작성 중/삭제 중인지
this.type(); // 실제 작성하는 함수 실행시켜 둠
};
// 인스턴스 없어도 생성자 함수 호출 가능
new TypeWriter(txtElement, words);
TypeWriter.prototype.type = function() {
// 현재 배열 안 데이터 가져오기
var current = this.wordIndex % this.words.length;
var fullTxt = this.words[current];
// 각 단어에서 필요한 부분만 잘라서 가져오기
// substring(start, end): start부터 end 직전까지. 인자 1개면 start 이후부터 가져오기
if(this.isDeleting) {
this.txt = fullTxt.substring(0, this.txt.length - 1);
} else {
this.txt = fullTxt.substring(0, this.txt.length + 1); // 글자수보다 1개 더까지 잘라내기
}
this.txtElement.textContent = this.txt;
}
if(!this.isDeleting && this.txt === fullTxt) {
this.isDeleting = true;
} else if (this.isDeleting && this.txt === ""){
this.isDeleting = false;
this.wordIndex++; // 다음 단어로 넘어가기
}
var that = this; // 중첩함수 안에서도 객체 선택하기 위한 코드
setTimeout(function() {
console.log(that);
// 멈추는 지점 추가
if(that.wordIndex<5) {
that.type();
}
}, 500);
var name = 'mango';
console.log("my name is " + name);
console.log(`my name is ${name}.`);
__proto__
, prototype
, constructor
등 특정 속성 혹은 객체와 그 속성을 찾는 방법이 섞여 있어서 헷갈렸다.html, css를 사용할 때와 다르게 좀더 논리적인 과정이 많이 필요해졌다고 느낀다. 디자인과 다르게 어느정도 순차적인 기능을 구현해야 하기 때문이라고 생각한다. 어서 진도를 나가서 웹사이트 기능을 만들어 보고 싶다.