JavaScript's "this":how it works, where it can trip you up
JavaScript’s “this”:how it works, where it can trip you up (당신이 실수를 유발하게 할 수 있는 “this”는 어떻게 작동하는가)
자바스크립트에서 특별한 변수 this는 비교적 복잡하다, 어디든지 가능하기 때문에, 객체지향적 설정에서 뿐만 아니라. 이 블로그 포스트에서는 어떻게 작동을 하는지, 어디서 문제를 일이키는지를 좋은 살례를 들어 마무리 짓도록 설명합니다.
this 이해는, 세개의 범주에에서 사용되어 질 수 있는 위치로 나누는게 가장 좋다.
함수에서 : this는 액스트라, 자주 암시적며, 파라미터이다.
함수 밖(최상위 계층 스코프에서) : ‘this’는 브라우저에서는 글로벌 객체로 Node.js에서는 모듈의 exports로 참조된다.
문자로 eval()에 전달 : eval() this의 직접 호출되냐 간접적으로 호출되느냐에 따라 현재 값을 가지고 오거나 또는 글로벌 객체로 설정한다.
1. this in functions (함수에서의 this)
함수는 세가지 다른 역활을 수행하여, 자바스크립트의 모든 호출 구조를 나타내기 때문에 this 사용의 가장 일반적인 방법이다.
Real fuctions (this는 sloppy mode에서는 글로벌 객체, strict mode에서는 undefined)
Constructors (this는 새롭게 인스턴스로 만들어진 것을 참조한다.)
Method (this는 메소드 호출한 자를 참조한다.)
1.1 this in real functions (진짜 함수에서 this)
real functions에서, this의 값은 mode에 의지된다:
Sloppy mode : this global object를 참조한다.(브라우저에서는 window)
function sloppyFunc() { console.log(this === window); // true } sloppyFunc();
Strict mode : this는 undefined값을 갖는다.
function strictFunc() { 'use strict'; console.log(this === undefined); // true } strictFunc();
this 는 (window or undefined)기본값으로 설정되는 내포된 파라미터이다. 당신은, 어떻게, call() 아니면 apply()를 호출하고 this의 값을 명쾌하게 명시하는 함수를 만들자.
function func(arg1, arg2) { console.log(this); // a console.log(arg1); // b console.log(arg2); // c } func.call('a', 'b', 'c'); // (this, arg1, arg2) func.apply('a', ['b', 'c']); // (this, arrayWithArgs)
1.2 this in constructors (생성자 this)
Function는 만약 새로운 operator(연사자)를 통해 호출하면 생성자가 된다. operator(연사자)는 새로운 Object를 만들고 this 통해 생성자를 넘긴다.
var savedThis; function Constr() { savedThis = this; } var inst = new Constr(); console.log(savedThis === inst); // true
Javascript에서 구현은, 새로운 operator(연산자) 대략 다음과 같이 본다(더 정확한 구현은 slightly more complex)
function newOperator(Constr, arrayWithArgs) { var thisValue = Object.create(Constr.prototype); Constr.apply(thisValue, arrayWithArgs); return thisValue; }
1.3 this in methods (메소드 this)
methods 에서, 그것들은 더 전형적인 객체지향 언어에 가깝다 : this는 리시버를 참조한다,메소드의 객체는 호출되어 진다.
var obj = { method: function () { console.log(this === obj); // true } } obj.method();
2. Top level scope this (Top-level scope에서 this)
browser에서 top-level scope는 global scope와 global object(window같) 참조하는 것이다.
<script> console.log(this === window); // true </script>
Node.js에서, 당신은 일반적으로 실행한다 모듈의 코드를. 그러기전에 탑 레벨 스코프는 이다. 특별한 모듈 스코프:
// `global` (not `window`) refers to global object: console.log(Math === global.Math); // true // `this` doesn’t refer to the global object: console.log(this !== global); // true // `this` refers to a module’s exports: console.log(this === module.exports); // true //
3. this in eval() (eval()에서 this)
eval()은 동적(real function 호출을 통해)이거나 정적(몇가지 다른 의미를 통해)으로 불릴 수 있다. 자세한 것은 여기를 계획 서술 되어졌다.
만약 eval()은 불려진다 정적으로, 이것은 글로벌 객체를 참조한다:
> (0,eval)('this === window') true
그러지만 eval()이 불려지면 동적으로, this 남다 eval()의 환경에서 똑같이. 예를들어:
// Real functions function sloppyFunc() { console.log(eval('this') === window); // true } sloppyFunc(); function strictFunc() { 'use strict'; console.log(eval('this') === undefined); // true } strictFunc(); // Constructors var savedThis; function Constr() { savedThis = eval('this'); } var inst = new Constr(); console.log(savedThis === inst); // true // Methods var obj = { method: function () { console.log(eval('this') === obj); // true } } obj.method();
4. this-related pitfalls () (this 관련된 위험)
거기에 3개의 this 관련된 위험이다 당신의 알아야 하는. 주목 각 경우마다, strict mode는 안전하게 만들고, 때문에 this는 real function에서 undefined이고 당신은 경고를 얻는다 잘못 되었을때
4.1 Pitfall : forgetting new (위험 : new를 잊는중)
만약에 당신이 불러오다 생성자를 그리고 잊다 새로운 연산자를, 당신은 우연이다 사용중인 그것이 real function에서 Hence는 this는 가지지 못한다 정확한 값을. sloppy mode에서 this는 window이고 당신은 만들것이다 global 변수를:
function Point(x, y) { this.x = x; this.y = y; } var p = Point(7, 5); // we forgot new! console.log(p === undefined); // true // Global variables have been created: console.log(x); // 7 console.log(y); // 5
고맙게도, 당신은 얻는다 경고를 strict mode에서(this === undefined)
function Point(x, y) { 'use strict'; this.x = x; this.y = y; } var p = Point(7, 5); // TypeError: Cannot set property 'x' of undefined
4.2 Pitfall : extracting methods improperly (위험 : 추출 부적절한 메소드)
만약 당신이 검색하면 메소드의 값을 (대신에 그것을 불러오는), 당신은 되돌아온다 함수의 메소드가. 호출은 결과의 값을 함수의 호출에서, 메소드 호출이 아니다. 이것은 추출의 종류 발생할 수 있다 당신이 통과할때 메소드를 매개변수에서 함수 또는 메소드 호출에서. Real-world 예제에서 불러온다 setTimeout() 그리고 등록한다 이벤트 핸들러를. 나는 사용할 것이다 함수를 callIt()이란 시뮬레이이션 this에 동시일 경우에 사용
/** Similar to setTimeout() and setImmediate() */ function callIt(func) { func(); }
만약에 호출하면 당신이 sloppy-mode에서 함수 메소드를 this는 참조한다 글러벌 객체와 글로벌 변수를 만들어진
var counter = { count: 0, // Sloppy-mode method inc: function () { this.count++; } } callIt(counter.inc); // Didn’t work: console.log(counter.count); // 0 // Instead, a global variable has been created // (NaN is result of applying ++ to undefined): console.log(count); // NaN
만약에 당신이 호출하면 strict-mode에서 함수의 메소드를 this는 undefined 이다. 것 일을 안하는, 어니하나. 그러나 적어도 당신은 얻는다 경고를 :
var counter = { count: 0, // Strict-mode method inc: function () { 'use strict'; this.count++; } } callIt(counter.inc); // TypeError: Cannot read property 'count' of undefined console.log(counter.count);
var counter = { count: 0, inc: function () { this.count++; } } callIt(counter.inc.bind(counter)); // It worked! console.log(counter.count); // 1
bind()는 만들었다 새로운 함수를 항상 받을수 있는 this 값은 카운터에 있다.
4.3 Pitfall:shadowing this(위험 : shadowing에서 this)
당신이 사용할때 진짜 할수를 메소드안에서, 그것은 쉽다 잊는것이 농자에서 이것 자신이 this를 갖는 다는거 (비록 그것은 그것을 위해 필요하지 않다). 따라서 당신은 할수 없다 참조를 폼에서 메소드를 this 메소드의 , 때문에 그것은 쉐도우이다. 보자 예를 것을 잘못된 :
var obj = { name: 'Jane', friends: [ 'Tarzan', 'Cheeta' ], loop: function () { 'use strict'; this.friends.forEach( function (friend) { console.log(this.name+' knows '+friend); } ); } }; obj.loop(); // TypeError: Cannot read property 'name' of undefined
이전의 예제에서, this.name는 실패이고, 때문에 함수의 this는 undefined 이다. 그것은 같지 않다 this 만큼 loop() 메소드에서. 거기에는 있다 세가지 방법 고적적인 … this
Fix 1 : that = this. 맡긴다 this는 변수 그림자가 아니다(다른 인기있는 이름은 self이다) 그리고 사용된다 하나가.
loop: function () { 'use strict'; var that = this; this.friends.forEach(function (friend) { console.log(that.name+' knows '+friend); }); }
Fix 2 : bind(). 사용한다 bind()를 만들어서 함수를 this는 항상 가진다 연결된 값을 (메소드 this 다음에제에서).
loop: function () { 'use strict'; this.friends.forEach(function (friend) { console.log(this.name+' knows '+friend); }.bind(this)); }
Fix 3 : forEach’s second parameter. 이 메소드는 가진다 두번째 파라미터를 값은 전달한다 콜백을 this.
loop: function () { 'use strict'; this.friends.forEach(function (friend) { console.log(this.name+' knows '+friend); }, this); }
5. Best practices(가장 좋은 사례)
개념적으로, 나는 생각한다 실제 함수에서 가지지 않은 그들 자신의 this이고 생각한다 앞서 언급한 수정들은 따라간다 오해를. ECMAScript 6은 제공한다 this 접근을 arrow 함수를 통해 - 함수는 없이 그들 자신의 this. 각 함수들 안에서 당신은 자유로울 수 있습니다 사용이 this, 때문에 거기에 그림자는 아니다:
loop: function () { 'use strict'; // The parameter of forEach() is an arrow function this.friends.forEach(friend => { // `this` is loop’s `this` console.log(this.name+' knows '+friend); }); } 나는 같지 않다 API들은 사용한다 `this` 이외의 파라미터 실제 함수들에서: ```javascript beforeEach(function () { this.addMatchers({ toBeInRange: function (start, end) { ... } }); });
돌리면 각 암시적 파라미터를 명시적 파라미터로 더 분명하게 만들고 호환된다 arrow 함수들과도
beforeEach(api => { api.addMatchers({ toBeInRange(start, end) { ... } }); });
http://www.2ality.com/2014/05/this.html