본문 바로가기

미드영어 공부

자바스크립트(Javascript) new fn() and f() 차이점


자바스크립트(Javascript) new fn() and f()


자바스크립트에서 함수들은 우리가 아는 그냥 함수처럼 사용 될 수 있고 C++나 JAVA에서 처럼 new 라는 키워드로 instantiate할 수 있다.


예를들어 아래와 같은 코드가 있다고 보자


아래에는 Person이라는 함수가 있다 여기에 name을 전달 해서 

this.name에 저장을 할 수 있다.


1
2
3
4
5
6
7
function Person(name){
    this.name = name

   this.greet = function(){
      console.log(this.name);
    }
}
 
cs


여기에 아래와 같이 prototype.greeting으로 functionality를 좀더 추가 할 수 있다.

이럴 때 아래 3 console.log에 값은 어떻게 나올까 ? 


1
2
3
4
5
6
7
8
Person.prototype.greeting = function () {
    console.log('greetings ' + this.name)
}
 
const john = new Person('John');
console.log(john);
john.greet();
john.greeting();
cs



라인 6 결과 - new라는 키워드를 사용했기 때문에 Person이라는 object를 리턴해 주게되고 Person이라는 오브젝트에는 

우리가 앞서 정의한 prototype.greeting도 추가가 되어 있다.


1
2
3
4
5
6
7
8
Person
greet:()
name:"John"
__proto__:Object
constructor:
    Person(name)
        greeting:()
        __proto__:Object
cs


라인 7 결과 - John

라인 8 결과 - greetings John 


결과 적으로 Person 함수 안에 있는 것들은 Person이라는 것에 bind되서 this로 접근이 가능하다 



하지만 아래와 같이 Person을 함수와 같이 사용 하면 어떻까 .

Jen은 undefined가 될 것이다 왜냐 하면 함수가 아무것도 리턴 하지 않았으니까 

다른 것들도 undefined is not a function 같은 에러가 날 것이다.


1
2
3
4
5
const Jen = Person('Jen');
console.log(Jen);
Jen.greeting();
console.log(Jen.name);
Jen.greet();
cs



new 키워드를 사용해서 함수를 호출 하는 것은 아래 보이는 코드가 constructor에서 실행 되는 것과 같다. 단지 public으로 ..


 this.name = name

 this.greet = function(){
     console.log(this.name);
 }


'미드영어 공부' 카테고리의 다른 글

React-native troubleshoot 리스트  (0) 2017.03.17
Javascript 클로저 ( closure )  (0) 2017.03.14
Laravel 5 / vue 2 튜토리얼  (0) 2017.01.21