You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
The`instanceof`operator allows to check whether an object belongs to a certain class. It also takes inheritance into account.
`instanceof`연산자는 객체가 특정 클래스에 속해 있는지 없는지를 검사합니다. 또한, 상속 관계에 있는지 확인합니다.
Such a check may be necessary in many cases, here we'll use it for building a *polymorphic* function, the one that treats arguments differently depending on their type.
확인하는 기능은 많은 경우에서 필수적인데, 여기에 매개변수의 타입때문에 처리하는 법이 달라지는 *다형적인* 함수를 빌드하기 위해 사용할 것입니다.
##Theinstanceofoperator [#ref-instanceof]
## instanceof연산자 [#ref-instanceof]
The syntax is:
문법은 아래와 같습니다.
```js
obj instanceof Class
```
It returns `true` if `obj` belongs to the`Class` or a class inheriting from it.
`obj`가`Class`에 속해 있거나 상속하고 있다면, true를 반환합니다.
For instance:
예시:
```js run
class Rabbit {}
let rabbit = new Rabbit();
//is it an object of Rabbit class?
//rabbit이 Rabbit class에 속해있는지 물어봅니다.
*!*
alert( rabbit instanceof Rabbit ); // true
*/!*
```
It also works with constructor functions:
instanceof는 생성자 함수에서도 동작합니다.
```js run
*!*
//instead of class
//클래스 대신 함수를 사용하였습니다.
function Rabbit() {}
*/!*
alert( new Rabbit() instanceof Rabbit ); // true
```
...And with built-in classes like `Array`:
또한, `Array` 같은 클래스의 내장함수로써의 기능도 있습니다.
```js run
let arr = [1, 2, 3];
alert( arr instanceof Array ); // true
alert( arr instanceof Object ); // true
```
Please note that`arr` also belongs to the`Object`class. That's because`Array` prototypically inherits from`Object`.
`arr`은 또한,`Object`class에 속해있다는 것을 기억하세요.`Array`는 원래`Object`를 상속하고 있습니다.
Normally, `instanceof`operator examines the prototype chain for the check. We can also set a custom logic in the static method`Symbol.hasInstance`.
보통, `instanceof`연산자는 프로토타입 체인의 확인을 검사해줍니다. 또한, 정적 메서드`Symbol.hasInstance`로 커스텀 로직을 설정할수 있습니다.
The algorithm of`obj instanceof Class` works roughly as follows:
`obj instanceof Class`의 알고리즘은 대략적으로 다음과 같이 동작합니다.
1.If there's a static method`Symbol.hasInstance`, then just call it:`Class[Symbol.hasInstance](obj)`.It should return either`true`or `false`, and we're done. That's how we can customize the behavior of `instanceof`.
1.정적 메서드`Symbol.hasInstance`가 있다고 가정한다면, 그저 호출하면 됩니다.`Class[Symbol.hasInstance](obj)`.결과는`true`나 `false`값을 반환할 것입니다. 다음은 `instanceof`를 어떻게 커스텀 하는지에 대한 예시입니다.
For example:
예시:
```js run
// setup instanceOf check that assumes that
//anything withcanEatproperty is an animal
//instanceOf는canEat프로퍼티가 aniaml인지 확인하는 것입니다.
class Animal {
static [Symbol.hasInstance](obj) {
if (obj.canEat) return true;
Expand All
@@ -65,24 +65,24 @@ The algorithm of `obj instanceof Class` works roughly as follows:
let obj = { canEat: true };
alert(obj instanceof Animal); // true:Animal[Symbol.hasInstance](obj) is called
alert(obj instanceof Animal); // true:Animal에서 저희가 커스터마이즈한Symbol.hasInstance가 호출 되었기 때문에 true를 리턴했습니다.
```
2.Most classes do not have`Symbol.hasInstance`. In that case, the standard logic is used:`obj instanceOf Class` checks whether`Class.prototype` equals to one of prototypes in the `obj` prototype chain.
2.대부분 클래스는`Symbol.hasInstance`를 가지고 있지 않습니다. 이러한 경우, 일반적인 로직이 사용될 것입니다.`obj instanceOf Class`는`Class.prototype`이 `obj` 프로토 체인 내부의 프로토타입 중 하나와 같은지 확인합니다.
Here's the illustration of what`rabbit instanceof Animal` compares with`Animal.prototype`:
여기에`rabbit instanceof Animal`의 무엇과`Animal.prototype`을 비교하는 지에 대한 그림이 있습니다.

By the way, there's also a method[objA.isPrototypeOf(objB)](mdn:js/object/isPrototypeOf), that returns `true` if `objA` is somewhere in the chain of prototypes for `objB`. So the test of `obj instanceof Class` can be rephrased as `Class.prototype.isPrototypeOf(obj)`.
그런데, `objA`가 `objB`의 프로토타입의 체인 어딘가에 있다면, `true`를 리턴하는[objA.isPrototypeOf(objB)](mdn:js/object/isPrototypeOf)라는 메서드가 있습니다.
It's funny, but the`Class`constructor itself does not participate in the check! Only the chain of prototypes and`Class.prototype` matters.
`Class`생성자 그 자체는 확인할 수 없지만, 오직 프르토타입 체인과`Class.prototype`은 매우 중요하므로 확인해야 합니다.
That can lead to interesting consequences when`prototype` property is changed after the object is created.
언제`prototype`프로퍼티가 객체가 생성된 후에 변화되는지에 따라 흥미로운 결과를 이끌어 낼수 있습니다.
Like here:
아래와 같이 말이죠.
```js run
function Rabbit() {}
let rabbit = new Rabbit();
//changed the prototype
//프로토타입을 변형했습니다.
Rabbit.prototype = {};
// ...not a rabbit any more!
// ...더이상 Rabbit이 아닙니다!
*!*
alert( rabbit instanceof Rabbit ); // false
*/!*
```
##Bonus:Object.prototype.toString for the type
##보너스: 타입을 위한Object.prototype.toString
We already know that plain objects are converted to string as`[object Object]`:
이미 여러분들은 평범한 객체들이`[object Object]`의 문자열로 변환되는 것에 대해 알고 있습니다.
```js run
let obj = {};
alert(obj); // [object Object]
alert(obj.toString()); //the same
alert(obj.toString()); //같습니다.
```
That's their implementation of`toString`. But there's a hidden feature that makes `toString` actually much more powerful than that. We can use it as an extended `typeof` and an alternative for`instanceof`.
그것은 바로`toString`으로 구현되어 있습니다. 그러나 `toString`은 실질적으로 그것이 가진 기능보다 더 강력하게 만들어 줄 수 있는 몇 가지 숨겨진 특징들이 있습니다. 확장된 기능으로써 `typeof`을 사용할수 있는데, 이것은`instanceof` 대신 사용할 수 있습니다.
Sounds strange? Indeed. Let's demystify.
이상하게 들리나요? 그럼 미스터리로 두죠.
By [specification](https://tc39.github.io/ecma262/#sec-object.prototype.tostring), the built-in `toString` can be extracted from the object and executed in the context of any other value. And its result depends on that value.
[이곳](https://tc39.github.io/ecma262/#sec-object.prototype.tostring)에 명시되어 있듯이, 객체와 실행중인 다른 값의 컨텍스트로부터 내장함수 `toString`을 사용하여 추출할 수 있습니다. 그리고 그 결과는 그 객체가 가진 값에 의존합니다.
-For a number, it will be`[object Number]`
-For a boolean, it will be`[object Boolean]`
-For `null`:`[object Null]`
-For`undefined`:`[object Undefined]`
-For arrays:`[object Array]`
-...etc (customizable).
-숫자의 경우, 그것은`[object Number]`가 될 것입니다.
-불린의 경우, 그것은`[object Boolean]`이 될 것입니다.
-null의 경우, 그것은`[object Null]`가 될 것입니다.
- `undefined`의 경우, 그것은`[object Undefined]`가 될 것입니다.
-배열의 경우, 그것은`[object Array]`가 될 것입니다.
-그외에 여러가지가 다양하게 있는데, 그것에 따라 맞춰집니다.
Let's demonstrate:
그럼 같이 한번 해결해볼까요?
```js run
//copytoStringmethod into a variable for convenience
Here we used [call](mdn:js/function/call) as described in the chapter [](info:call-apply-decorators) to execute the function`objectToString` in the context`this=arr`.
이번 챕터에서 [](info:call-apply-decorators)에 서술되어 있는 [call](mdn:js/function/call)는 함수`objectToString`은`this=arr` 컨텍스트에 실행하기 위해서 사용했습니다.
Internally, the`toString`algorithm examines`this` and returns the corresponding result. More examples:
내부적으로,`toString`알고리즘은`this`를 검사하고, 일치하는 결과를 반환합니다. 더 많은 예시를 살펴봅시다.
And `instanceof`operator really shines when we are working with a class hierarchy and want to check for the class taking into account inheritance.
그리고 `instanceof`연산자는 클래스 계층에 작업하거나, 상속을 고려하여 클래스를 확인 할 때, 정말 큰 빛을 발합니다.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.