prototype 연습문제

2022. 9. 6. 15:18Javascript

class Student {
  constructor(이름, 나이) {
    (this.name = 이름), (this.age = 나이);
  }
}
Student.prototype.sayHello = function() {
    console.log(`안녕 나는 ${this.name} 이야.`);
  };

Student.prototype.sayHi = () => {
  console.log(`안녕 나는 ${this.name} 이야.`);
};
var 학생1 = new Student("kim", 20);

console.log(학생1);
학생1.sayHello() //안녕 나는 kim 이야.
학생1.sayHi() //안녕 나는 undefined 이야.

function으로 쓴 것과 Arrow Function으로 작성한 것에서 this.name이 다르게 나오는 이유 ?

function의 this는 이 함수를 품고있는 object를 가리킨다.

두번 째 this 는 Arrow Function으로 작성했을 때 , 바로 위의 this를 받아서 쓰기 때문에. Student라는 Object를 가리키지 않음.

-> Window를 가리킨다.

Arrow Function은 일반 Function의 대체품이 아님.

 

 

Array.prototype.remove3 = function(){
    return this.filter(a => a !== 3)
}

Array.prototype.sayHi = function(){
    return console.log('good');
}

var arr1 = [1,2,3]

arr1.sayHi() //good
console.log(arr1.remove3()) //[1,2]

Array 프로토타입 커스텀 제작하기

'Javascript' 카테고리의 다른 글

Destructuring  (0) 2022.09.19
extends, super  (0) 2022.09.06
Async/Await  (0) 2022.09.04
Promise  (0) 2022.09.04
콜백함수  (0) 2022.08.23