function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHi = function () {
console.log('hihi');
}
const p1 = new Person('a', 20);
p1.sayHi();
class Person2 {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHi() {
console.log('hihi', this.name);
}
}
const p2 = new Person2('b', 30);
p2.sayHi();
// [1] / [2] 차이
// 클래스는 기본적으로 엄격모드(use strict) --> 자동 적용
// 클래스 메서드는 열거 대상이 아니다.--> 클래스와 같은 이름의 '프로토타입 객체'의 속성에 추가된 메서드들 열거 불가
// 생성자 함수
for(let i in p1) {
console.log(i); // name, age , sayHi
}
console.log('클래스 열거');
// 클래스
for(let i in p2) {
console.log(i); // name, age ... 클래스 메서드 (sayHi)는 열거(Enumerable) 대상이 아니다
}
// 어떤 객체를 다룰때 --> 그 객체의 모든 특성을 보고자 한다면 --> getOwnPropertyNames() 메서드 사용
// 정적 메서드 ---> Object.getOwnPropertyNames(객체명)
// ---> Object.getPrototypeOf() --> 지정된 객체 내부 Prototype 속성 값을 반환
const p1 = {
eat() {},
run() {},
rest() {}
};
class Person2 {
constructor(name, age) {
this.age = age;
this.name = name;
}
eat() {};
run() {};
rest() {};
};
const p2 = new Person2('psh', 30);
for (let i in p2) {
console.log('p2의 멤버들 = ' + i);
}
console.log(p1);
console.log(p2); // Person2의 메서드는 보이지 않는다.
console.log(Object.keys(p1)); // 배열 반환
console.log(Object.getPrototypeOf(p2)); // 클래스 생성시 만들어지는 클래스 prototype
console.log(Object.keys(Object.getPrototypeOf(p2))); // [] .. 클래스 생성하여 만들어진 객체는 리터럴 객체와는 다르게 출력되지 않는다
console.log(Object.getOwnPropertyNames(p1)); // console.log(Object.keys(p1)); 와 동일한 리턴
console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(p2))); // ['constructor', 'eat', 'run', 'rest']
[1]:
const dog1 = {
name: "멍멍이",
sound: "멍멍!",
say: function say() {
console.log(this.sound);
}
};
dog1.say();
[2]: 함수명 없이
const dog2 = {
name: "멍멍이",
sound: "멍멍!",
say: function() {
console.log(this.sound);
}
};
dog2.say();
[3]: function 키워드 없이 함수만 넣어도 인식
const dog3 = {
name: "멍멍이",
sound: "멍멍!",
say() {
console.log(this.sound);
}
};
dog3.say();
[4]: arrow function 불가 !!
const dog4 = {
name: "멍멍이",
sound: "멍멍!",
say: () => {
console.log(this.sound);
}
};
dog4.say(); // undefined .. function 키워드들은 자신이 속해있는 곳을 가리키게 되는데 ... 화살표 함수는 this를 자신이 속해있는곳으로 연결하지 않음..