2017-09-27 9 views
0

JS ES6 클래스를 이해하려고하는데 "최대 호출 스택 크기가 초과되었습니다."라는 메시지가 나타나면 "this"로 대답합니다. 변수. 이 예제를 살펴 보겠습니다.ES6 JS 클래스 밑줄 집합 및 get 메서드 반환 "최대 호출 스택 크기 초과"

class Human { 
    constructor(age) { 
    this.age = age; 
    // "this._age = age;" output: 
    // Property age of instance without underscore: 34 
    // Property age of instance with underscore: 34 
    } 

    get age() { 
    return this._age; 
    // Without underscore error: "Uncaught RangeError: Maximum call stack size exceeded" 
    } 

    set age(age) { 
    this._age = age; 
    // Without underscore error: "Uncaught RangeError: Maximum call stack size exceeded" 
    console.log(`Without underscore: ${this.age}`); 
    console.log(`With underscore: ${this._age}`); 
    } 
} 

let john = new Human(34); 
console.log(`Property age of instance without underscore: ${john.age}`); 
console.log(`Property age of instance with underscore: ${john._age}`); 

get 및 set 메서드에서 그 밑줄을 사용해야하는 이유는 무엇입니까? 왜 출력물이 생성자에서 사용할 때와 같이 변하는가? 인스턴스 속성을 사용하려고 할 때 밑줄을 사용하거나 사용하지 않는 미터가없는 이유는 무엇입니까? mdn 문서에는 밑줄이 전혀 없습니다.

답변

4

set age을 사용하는 요점은 사용자가 age이라는 설정자를 정의한다는 것입니다.

세터의 구현이 this.age = <new value> 일 경우 이 되풀이 세터를 호출합니다.

age이라는 설정자가없고 age이라는 멤버 변수를 설정하려고 시도 할 수 없습니다. 그들은 age_age과 같이 다른 것으로 불려야합니다.

0

댓글이 너무 깁니다. Meagar의 (올바른) 대답에 추가하려면 :

set foo (val) { 
    // empty 
} 

설탕가이 이상 :

instance.foo = val; 

그래서 때마다 다른 코드가 세터가 호출되는 foo 속성을 설정합니다. 이유는 설정자이 존재하기 때문에 값을 유효한지 확인하기 위해 다른 작업을 수행하려는 경우가 있습니다. 당신이 세터를 가지고 호출 될 때 그래서 당신은 그런 세터 당신이 실제로 자신을 호출하는

set foo (val) { 
    this.foo = val; 
} 

instance.foo = val; 

을 수행 할 때.