From ee778d6eea54935fd05022e0ba8c49456003381a Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:48:24 +0100 Subject: unslug ko: move --- .../reference/classes/class_fields/index.html | 396 --------------- .../classes/public_class_fields/index.html | 396 +++++++++++++++ .../reference/functions/arrow_functions/index.html | 465 ++++++++++++++++++ .../index.html" | 465 ------------------ .../global_objects/bigint/prototype/index.html | 59 --- .../global_objects/boolean/prototype/index.html | 82 ---- .../global_objects/date/prototype/index.html | 183 ------- .../internalerror/prototype/index.html | 101 ---- .../intl/datetimeformat/prototype/index.html | 87 ---- .../intl/numberformat/prototype/index.html | 86 ---- .../global_objects/map/prototype/index.html | 87 ---- .../global_objects/number/prototype/index.html | 91 ---- .../global_objects/object/prototype/index.html | 219 --------- .../global_objects/promise/prototype/index.html | 72 --- .../global_objects/proxy/handler/apply/index.html | 154 ------ .../global_objects/proxy/handler/index.html | 82 ---- .../global_objects/proxy/proxy/apply/index.html | 154 ++++++ .../global_objects/proxy/proxy/index.html | 82 ++++ .../global_objects/set/prototype/index.html | 87 ---- .../sharedarraybuffer/prototype/index.html | 66 --- .../global_objects/string/prototype/index.html | 219 --------- .../syntaxerror/prototype/index.html | 127 ----- .../global_objects/typedarray/prototype/index.html | 176 ------- .../global_objects/weakmap/prototype/index.html | 143 ------ .../global_objects/weakset/prototype/index.html | 142 ------ .../webassembly/global/prototype/index.html | 70 --- .../operators/arithmetic_operators/index.html | 291 ----------- .../operators/assignment_operators/index.html | 395 --------------- .../operators/bitwise_operators/index.html | 541 --------------------- .../operators/comparison_operators/index.html | 216 -------- .../operators/operator_precedence/index.html | 462 ++++++++++++++++++ .../index.html" | 250 ---------- .../index.html" | 462 ------------------ .../reference/statements/default/index.html | 122 ----- 34 files changed, 1559 insertions(+), 5471 deletions(-) delete mode 100644 files/ko/web/javascript/reference/classes/class_fields/index.html create mode 100644 files/ko/web/javascript/reference/classes/public_class_fields/index.html create mode 100644 files/ko/web/javascript/reference/functions/arrow_functions/index.html delete mode 100644 "files/ko/web/javascript/reference/functions/\354\225\240\353\241\234\354\232\260_\355\216\221\354\205\230/index.html" delete mode 100644 files/ko/web/javascript/reference/global_objects/bigint/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/boolean/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/date/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/internalerror/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/intl/numberformat/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/map/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/number/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/object/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/promise/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/proxy/handler/apply/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/proxy/handler/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/proxy/proxy/apply/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/proxy/proxy/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/set/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/string/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/syntaxerror/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/weakmap/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/weakset/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/global/prototype/index.html delete mode 100644 files/ko/web/javascript/reference/operators/arithmetic_operators/index.html delete mode 100644 files/ko/web/javascript/reference/operators/assignment_operators/index.html delete mode 100644 files/ko/web/javascript/reference/operators/bitwise_operators/index.html delete mode 100644 files/ko/web/javascript/reference/operators/comparison_operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/operator_precedence/index.html delete mode 100644 "files/ko/web/javascript/reference/operators/\353\205\274\353\246\254_\354\227\260\354\202\260\354\236\220(logical_operators)/index.html" delete mode 100644 "files/ko/web/javascript/reference/operators/\354\227\260\354\202\260\354\236\220_\354\232\260\354\204\240\354\210\234\354\234\204/index.html" delete mode 100644 files/ko/web/javascript/reference/statements/default/index.html (limited to 'files/ko/web/javascript/reference') diff --git a/files/ko/web/javascript/reference/classes/class_fields/index.html b/files/ko/web/javascript/reference/classes/class_fields/index.html deleted file mode 100644 index 959c65fada..0000000000 --- a/files/ko/web/javascript/reference/classes/class_fields/index.html +++ /dev/null @@ -1,396 +0,0 @@ ---- -title: Class fields -slug: Web/JavaScript/Reference/Classes/Class_fields -translation_of: Web/JavaScript/Reference/Classes/Public_class_fields ---- -
{{JsSidebar("Classes")}}
- -
-

This page describes experimental features.

- -

Both Public and private field declarations are an experimental feature (stage 3) proposed at TC39, the JavaScript standards committee.

- -

Support in browsers is limited, but the feature can be used through a build step with systems like Babel. See the compat information below.

-
- -

Public fields

- -

static fields와 instance의 public fields 는 둘 다 writable, enumerable, configurable 한 프로퍼티들이다. 예를들면, 정 반대인 private 과는 다르게, unlike their private counterparts, static fields는 프로토타입 상속에 관여한다.

- -

Public static fields

- -

Public static fields 는 클래스에서 생성하는 모든 인스턴스에 대한 필드가 아닌, 클래스마다 단 한개의 필드가 존재하기를 원할 때 유용하게 사용할 수 있다. Public fields는 캐시, 고정된 설정값, 또는 인스턴스 간 복제할 필요가 없는 어떤 데이터 등에 유용하게 쓰일 수 있다.

- -

Public static fields are declared using the static keyword. They are added to the class constructor at the time of class evaluation using {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}}. They are accessed again from the class constructor.

- -
class ClassWithStaticField {
-  static staticField = 'static field'
-}
-
-console.log(ClassWithStaticField.staticField)
-// expected output: "static field"​
-
- -

Fields without initializers are initialized to undefined.

- -
class ClassWithStaticField {
-  static staticField
-}
-
-console.assert(ClassWithStaticField.hasOwnProperty('staticField'))
-console.log(ClassWithStaticField.staticField)
-// expected output: "undefined"
- -

Public static fields are not reinitialized on subclasses, but can be accessed via the prototype chain.

- -
class ClassWithStaticField {
-  static baseStaticField = 'base field'
-}
-
-class SubClassWithStaticField extends ClassWithStaticField {
-  static subStaticField = 'sub class field'
-}
-
-console.log(SubClassWithStaticField.subStaticField)
-// expected output: "sub class field"
-
-console.log(SubClassWithStaticField.baseStaticField)
-// expected output: "base field"
- -

When initializing fields, this refers to the class constructor. You can also reference it by name, and use super to get the superclass constructor (if one exists).

- -
class ClassWithStaticField {
-  static baseStaticField = 'base static field'
-  static anotherBaseStaticField = this.baseStaticField
-
-  static baseStaticMethod() { return 'base static method output' }
-}
-
-class SubClassWithStaticField extends ClassWithStaticField {
-  static subStaticField = super.baseStaticMethod()
-}
-
-console.log(ClassWithStaticField.anotherBaseStaticField)
-// expected output: "base static field"
-
-console.log(SubClassWithStaticField.subStaticField)
-// expected output: "base static method output"
-
- -

Public instance fields

- -

Public instance fields exist on every created instance of a class. By declaring a public field, you can ensure the field is always present, and the class definition is more self-documenting.

- -

Public instance fields are added with {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}} either at construction time in the base class (before the constructor body runs), or just after super() returns in a subclass.

- -
class ClassWithInstanceField {
-  instanceField = 'instance field'
-}
-
-const instance = new ClassWithInstanceField()
-console.log(instance.instanceField)
-// expected output: "instance field"
- -

Fields without initializers are initialized to undefined.

- -
class ClassWithInstanceField {
-  instanceField
-}
-
-const instance = new ClassWithInstanceField()
-console.assert(instance.hasOwnProperty('instanceField'))
-console.log(instance.instanceField)
-// expected output: "undefined"
- -

Like properties, field names may be computed.

- -
const PREFIX = 'prefix'
-
-class ClassWithComputedFieldName {
-    [`${PREFIX}Field`] = 'prefixed field'
-}
-
-const instance = new ClassWithComputedFieldName()
-console.log(instance.prefixField)
-// expected output: "prefixed field"
- -

When initializing fields this refers to the class instance under construction. Just as in public instance methods, if you're in a subclass you can access the superclass prototype using super.

- -
class ClassWithInstanceField {
-  baseInstanceField = 'base field'
-  anotherBaseInstanceField = this.baseInstanceField
-  baseInstanceMethod() { return 'base method output' }
-}
-
-class SubClassWithInstanceField extends ClassWithInstanceField {
-  subInstanceField = super.baseInstanceMethod()
-}
-
-const base = new ClassWithInstanceField()
-const sub = new SubClassWithInstanceField()
-
-console.log(base.anotherBaseInstanceField)
-// expected output: "base field"
-
-console.log(sub.subInstanceField)
-// expected output: "base method output"
- -

Public methods

- -

Public static methods

- -

The static keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.

- -

{{EmbedInteractiveExample("pages/js/classes-static.html")}}

- - - -

The static methods are added to the class constructor with {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}} at class evaluation time. These methods are writable, non-enumerable, and configurable.

- -

Public instance methods

- -

As the name implies, public instance methods are methods available on class instances.

- -
class ClassWithPublicInstanceMethod {
-  publicMethod() {
-    return 'hello world'
-  }
-}
-
-const instance = new ClassWithPublicInstanceMethod()
-console.log(instance.publicMethod())
-// expected output: "hello worl​d"
- -

Public instance methods are added to the class prototype at the time of class evaluation using {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}}. They are writable, non-enumerable, and configurable.

- -

You may make use of generator, async, and async generator functions.

- -
class ClassWithFancyMethods {
-  *generatorMethod() { }
-  async asyncMethod() { }
-  async *asyncGeneratorMethod() { }
-}
- -

Inside instance methods, this refers to the instance itself. In subclasses, super lets you access the superclass prototype, allowing you to call methods from the superclass.

- -
class BaseClass {
-  msg = 'hello world'
-  basePublicMethod() {
-    return this.msg
-  }
-}
-
-class SubClass extends BaseClass {
-  subPublicMethod() {
-    return super.basePublicMethod()
-  }
-}
-
-const instance = new SubClass()
-console.log(instance.subPublicMethod())
-// expected output: "hello worl​d"
-
- -

Getters and setters are special methods that bind to a class property and are called when that property is accessed or set. Use the get and set syntax to declare a public instance getter or setter.

- -
class ClassWithGetSet {
-  #msg = 'hello world'
-  get msg() {
-    return this.#msg
-  }
-  set msg(x) {
-    this.#msg = `hello ${x}`
-  }
-}
-
-const instance = new ClassWithGetSet()
-console.log(instance.msg)
-// expected output: "hello worl​d"
-
-instance.msg = 'cake'
-console.log(instance.msg)
-// expected output: "hello cake"
-
- -

Private fields

- -

Private static fields 

- -

Private fields are accessible on the class constructor from inside the class declaration itself.

- -

The limitation of static variables being called by only static methods still holds. 

- -
class ClassWithPrivateStaticField {
-  static #PRIVATE_STATIC_FIELD
-
-  static publicStaticMethod() {
-    ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD = 42
-    return ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD
-  }
-}
-
-assert(ClassWithPrivateStaticField.publicStaticMethod() === 42)
- -

Private static fields are added to the class constructor at class evaluation time.

- -

There is a provenance restriction on private static fields. Only the class which defines the private static field can access the field.

- -

This can lead to unexpected behaviour when using this.

- -
class BaseClassWithPrivateStaticField {
-  static #PRIVATE_STATIC_FIELD
-
-  static basePublicStaticMethod() {
-    this.#PRIVATE_STATIC_FIELD = 42
-    return this.#PRIVATE_STATIC_FIELD
-  }
-}
-
-class SubClass extends BaseClassWithPrivateStaticField { }
-
-assertThrows(() => SubClass.basePublicStaticMethod(), TypeError)
-
- -

Private instance fields

- -

Private instance fields are declared with # names (pronounced "hash names"), which are identifiers prefixed with #. The # is a part of the name itself. It is used for declaration and accessing as well.

- -

The encapsulation is enforced by the language. It is a syntax error to refer to # names from out of scope.

- -
class ClassWithPrivateField {
-  #privateField
-
-  constructor() {
-    this.#privateField = 42
-    this.#randomField = 666 // Syntax error
-  }
-}
-
-const instance = new ClassWithPrivateField()
-instance.#privateField === 42 // Syntax error
-
- -

Private Methods

- -

Private static methods

- -

Like their public equivalent, private static methods are called on the class itself, not instances of the class. Like private static fields, they are only accessible from inside the class declaration.

- -

Private static methods may be generator, async, and async generator functions.

- -
class ClassWithPrivateStaticMethod {
-    static #privateStaticMethod() {
-        return 42
-    }
-
-    static publicStaticMethod1() {
-        return ClassWithPrivateStaticMethod.#privateStaticMethod();
-    }
-
-    static publicStaticMethod2() {
-        return this.#privateStaticMethod();
-    }
-}
-
-assert(ClassWithPrivateStaticField.publicStaticMethod1() === 42);
-assert(ClassWithPrivateStaticField.publicStaticMethod2() === 42);
-
- -

This can lead to unexpected behaviour when using this(because this binding rule applies).

- -
class Base {
-    static #privateStaticMethod() {
-        return 42;
-    }
-    static publicStaticMethod1() {
-        return Base.#privateStaticMethod();
-    }
-    static publicStaticMethod2() {
-        return this.#privateStaticMethod();
-    }
-}
-
-class Derived extends Base {}
-
-console.log(Derived.publicStaticMethod1()); // 42
-console.log(Derived.publicStaticMethod2()); // TypeError
-
- -

Private instance methods

- -

Private instance methods are methods available on class instances whose access is restricted in the same manner as private instance fields.

- -
class ClassWithPrivateMethod {
-  #privateMethod() {
-    return 'hello world'
-  }
-
-  getPrivateMessage() {
-      return this.#privateMethod()
-  }
-}
-
-const instance = new ClassWithPrivateMethod()
-console.log(instance.getPrivateMessage())
-// expected output: "hello worl​d"
- -

Private instance methods may be generator, async, or async generator functions. Private getters and setters are also possible:

- -
class ClassWithPrivateAccessor {
-  #message
-
-  get #decoratedMessage() {
-    return `✨${this.#message}✨`
-  }
-  set #decoratedMessage(msg) {
-    this.#message = msg
-  }
-
-  constructor() {
-    this.#decoratedMessage = 'hello world'
-    console.log(this.#decoratedMessage)
-  }
-}
-
-new ClassWithPrivateAccessor();
-// expected output: "✨hello worl​d✨"
-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
FieldDefinition productionStage 3
- -

Browser compatibility

- -

Public class fields

- - - -

{{Compat("javascript.classes.public_class_fields")}}

- -

Private class fields

- - - -

{{Compat("javascript.classes.private_class_fields")}}

- -

See also

- - diff --git a/files/ko/web/javascript/reference/classes/public_class_fields/index.html b/files/ko/web/javascript/reference/classes/public_class_fields/index.html new file mode 100644 index 0000000000..959c65fada --- /dev/null +++ b/files/ko/web/javascript/reference/classes/public_class_fields/index.html @@ -0,0 +1,396 @@ +--- +title: Class fields +slug: Web/JavaScript/Reference/Classes/Class_fields +translation_of: Web/JavaScript/Reference/Classes/Public_class_fields +--- +
{{JsSidebar("Classes")}}
+ +
+

This page describes experimental features.

+ +

Both Public and private field declarations are an experimental feature (stage 3) proposed at TC39, the JavaScript standards committee.

+ +

Support in browsers is limited, but the feature can be used through a build step with systems like Babel. See the compat information below.

+
+ +

Public fields

+ +

static fields와 instance의 public fields 는 둘 다 writable, enumerable, configurable 한 프로퍼티들이다. 예를들면, 정 반대인 private 과는 다르게, unlike their private counterparts, static fields는 프로토타입 상속에 관여한다.

+ +

Public static fields

+ +

Public static fields 는 클래스에서 생성하는 모든 인스턴스에 대한 필드가 아닌, 클래스마다 단 한개의 필드가 존재하기를 원할 때 유용하게 사용할 수 있다. Public fields는 캐시, 고정된 설정값, 또는 인스턴스 간 복제할 필요가 없는 어떤 데이터 등에 유용하게 쓰일 수 있다.

+ +

Public static fields are declared using the static keyword. They are added to the class constructor at the time of class evaluation using {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}}. They are accessed again from the class constructor.

+ +
class ClassWithStaticField {
+  static staticField = 'static field'
+}
+
+console.log(ClassWithStaticField.staticField)
+// expected output: "static field"​
+
+ +

Fields without initializers are initialized to undefined.

+ +
class ClassWithStaticField {
+  static staticField
+}
+
+console.assert(ClassWithStaticField.hasOwnProperty('staticField'))
+console.log(ClassWithStaticField.staticField)
+// expected output: "undefined"
+ +

Public static fields are not reinitialized on subclasses, but can be accessed via the prototype chain.

+ +
class ClassWithStaticField {
+  static baseStaticField = 'base field'
+}
+
+class SubClassWithStaticField extends ClassWithStaticField {
+  static subStaticField = 'sub class field'
+}
+
+console.log(SubClassWithStaticField.subStaticField)
+// expected output: "sub class field"
+
+console.log(SubClassWithStaticField.baseStaticField)
+// expected output: "base field"
+ +

When initializing fields, this refers to the class constructor. You can also reference it by name, and use super to get the superclass constructor (if one exists).

+ +
class ClassWithStaticField {
+  static baseStaticField = 'base static field'
+  static anotherBaseStaticField = this.baseStaticField
+
+  static baseStaticMethod() { return 'base static method output' }
+}
+
+class SubClassWithStaticField extends ClassWithStaticField {
+  static subStaticField = super.baseStaticMethod()
+}
+
+console.log(ClassWithStaticField.anotherBaseStaticField)
+// expected output: "base static field"
+
+console.log(SubClassWithStaticField.subStaticField)
+// expected output: "base static method output"
+
+ +

Public instance fields

+ +

Public instance fields exist on every created instance of a class. By declaring a public field, you can ensure the field is always present, and the class definition is more self-documenting.

+ +

Public instance fields are added with {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}} either at construction time in the base class (before the constructor body runs), or just after super() returns in a subclass.

+ +
class ClassWithInstanceField {
+  instanceField = 'instance field'
+}
+
+const instance = new ClassWithInstanceField()
+console.log(instance.instanceField)
+// expected output: "instance field"
+ +

Fields without initializers are initialized to undefined.

+ +
class ClassWithInstanceField {
+  instanceField
+}
+
+const instance = new ClassWithInstanceField()
+console.assert(instance.hasOwnProperty('instanceField'))
+console.log(instance.instanceField)
+// expected output: "undefined"
+ +

Like properties, field names may be computed.

+ +
const PREFIX = 'prefix'
+
+class ClassWithComputedFieldName {
+    [`${PREFIX}Field`] = 'prefixed field'
+}
+
+const instance = new ClassWithComputedFieldName()
+console.log(instance.prefixField)
+// expected output: "prefixed field"
+ +

When initializing fields this refers to the class instance under construction. Just as in public instance methods, if you're in a subclass you can access the superclass prototype using super.

+ +
class ClassWithInstanceField {
+  baseInstanceField = 'base field'
+  anotherBaseInstanceField = this.baseInstanceField
+  baseInstanceMethod() { return 'base method output' }
+}
+
+class SubClassWithInstanceField extends ClassWithInstanceField {
+  subInstanceField = super.baseInstanceMethod()
+}
+
+const base = new ClassWithInstanceField()
+const sub = new SubClassWithInstanceField()
+
+console.log(base.anotherBaseInstanceField)
+// expected output: "base field"
+
+console.log(sub.subInstanceField)
+// expected output: "base method output"
+ +

Public methods

+ +

Public static methods

+ +

The static keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.

+ +

{{EmbedInteractiveExample("pages/js/classes-static.html")}}

+ + + +

The static methods are added to the class constructor with {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}} at class evaluation time. These methods are writable, non-enumerable, and configurable.

+ +

Public instance methods

+ +

As the name implies, public instance methods are methods available on class instances.

+ +
class ClassWithPublicInstanceMethod {
+  publicMethod() {
+    return 'hello world'
+  }
+}
+
+const instance = new ClassWithPublicInstanceMethod()
+console.log(instance.publicMethod())
+// expected output: "hello worl​d"
+ +

Public instance methods are added to the class prototype at the time of class evaluation using {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}}. They are writable, non-enumerable, and configurable.

+ +

You may make use of generator, async, and async generator functions.

+ +
class ClassWithFancyMethods {
+  *generatorMethod() { }
+  async asyncMethod() { }
+  async *asyncGeneratorMethod() { }
+}
+ +

Inside instance methods, this refers to the instance itself. In subclasses, super lets you access the superclass prototype, allowing you to call methods from the superclass.

+ +
class BaseClass {
+  msg = 'hello world'
+  basePublicMethod() {
+    return this.msg
+  }
+}
+
+class SubClass extends BaseClass {
+  subPublicMethod() {
+    return super.basePublicMethod()
+  }
+}
+
+const instance = new SubClass()
+console.log(instance.subPublicMethod())
+// expected output: "hello worl​d"
+
+ +

Getters and setters are special methods that bind to a class property and are called when that property is accessed or set. Use the get and set syntax to declare a public instance getter or setter.

+ +
class ClassWithGetSet {
+  #msg = 'hello world'
+  get msg() {
+    return this.#msg
+  }
+  set msg(x) {
+    this.#msg = `hello ${x}`
+  }
+}
+
+const instance = new ClassWithGetSet()
+console.log(instance.msg)
+// expected output: "hello worl​d"
+
+instance.msg = 'cake'
+console.log(instance.msg)
+// expected output: "hello cake"
+
+ +

Private fields

+ +

Private static fields 

+ +

Private fields are accessible on the class constructor from inside the class declaration itself.

+ +

The limitation of static variables being called by only static methods still holds. 

+ +
class ClassWithPrivateStaticField {
+  static #PRIVATE_STATIC_FIELD
+
+  static publicStaticMethod() {
+    ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD = 42
+    return ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD
+  }
+}
+
+assert(ClassWithPrivateStaticField.publicStaticMethod() === 42)
+ +

Private static fields are added to the class constructor at class evaluation time.

+ +

There is a provenance restriction on private static fields. Only the class which defines the private static field can access the field.

+ +

This can lead to unexpected behaviour when using this.

+ +
class BaseClassWithPrivateStaticField {
+  static #PRIVATE_STATIC_FIELD
+
+  static basePublicStaticMethod() {
+    this.#PRIVATE_STATIC_FIELD = 42
+    return this.#PRIVATE_STATIC_FIELD
+  }
+}
+
+class SubClass extends BaseClassWithPrivateStaticField { }
+
+assertThrows(() => SubClass.basePublicStaticMethod(), TypeError)
+
+ +

Private instance fields

+ +

Private instance fields are declared with # names (pronounced "hash names"), which are identifiers prefixed with #. The # is a part of the name itself. It is used for declaration and accessing as well.

+ +

The encapsulation is enforced by the language. It is a syntax error to refer to # names from out of scope.

+ +
class ClassWithPrivateField {
+  #privateField
+
+  constructor() {
+    this.#privateField = 42
+    this.#randomField = 666 // Syntax error
+  }
+}
+
+const instance = new ClassWithPrivateField()
+instance.#privateField === 42 // Syntax error
+
+ +

Private Methods

+ +

Private static methods

+ +

Like their public equivalent, private static methods are called on the class itself, not instances of the class. Like private static fields, they are only accessible from inside the class declaration.

+ +

Private static methods may be generator, async, and async generator functions.

+ +
class ClassWithPrivateStaticMethod {
+    static #privateStaticMethod() {
+        return 42
+    }
+
+    static publicStaticMethod1() {
+        return ClassWithPrivateStaticMethod.#privateStaticMethod();
+    }
+
+    static publicStaticMethod2() {
+        return this.#privateStaticMethod();
+    }
+}
+
+assert(ClassWithPrivateStaticField.publicStaticMethod1() === 42);
+assert(ClassWithPrivateStaticField.publicStaticMethod2() === 42);
+
+ +

This can lead to unexpected behaviour when using this(because this binding rule applies).

+ +
class Base {
+    static #privateStaticMethod() {
+        return 42;
+    }
+    static publicStaticMethod1() {
+        return Base.#privateStaticMethod();
+    }
+    static publicStaticMethod2() {
+        return this.#privateStaticMethod();
+    }
+}
+
+class Derived extends Base {}
+
+console.log(Derived.publicStaticMethod1()); // 42
+console.log(Derived.publicStaticMethod2()); // TypeError
+
+ +

Private instance methods

+ +

Private instance methods are methods available on class instances whose access is restricted in the same manner as private instance fields.

+ +
class ClassWithPrivateMethod {
+  #privateMethod() {
+    return 'hello world'
+  }
+
+  getPrivateMessage() {
+      return this.#privateMethod()
+  }
+}
+
+const instance = new ClassWithPrivateMethod()
+console.log(instance.getPrivateMessage())
+// expected output: "hello worl​d"
+ +

Private instance methods may be generator, async, or async generator functions. Private getters and setters are also possible:

+ +
class ClassWithPrivateAccessor {
+  #message
+
+  get #decoratedMessage() {
+    return `✨${this.#message}✨`
+  }
+  set #decoratedMessage(msg) {
+    this.#message = msg
+  }
+
+  constructor() {
+    this.#decoratedMessage = 'hello world'
+    console.log(this.#decoratedMessage)
+  }
+}
+
+new ClassWithPrivateAccessor();
+// expected output: "✨hello worl​d✨"
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
FieldDefinition productionStage 3
+ +

Browser compatibility

+ +

Public class fields

+ + + +

{{Compat("javascript.classes.public_class_fields")}}

+ +

Private class fields

+ + + +

{{Compat("javascript.classes.private_class_fields")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/functions/arrow_functions/index.html b/files/ko/web/javascript/reference/functions/arrow_functions/index.html new file mode 100644 index 0000000000..02dc0d55e4 --- /dev/null +++ b/files/ko/web/javascript/reference/functions/arrow_functions/index.html @@ -0,0 +1,465 @@ +--- +title: 화살표 함수 +slug: Web/JavaScript/Reference/Functions/애로우_펑션 +tags: + - ECMAScript6 + - Functions + - Intermediate + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Functions/Arrow_functions +--- +
{{jsSidebar("Functions")}}
+ +

화살표 함수 표현(arrow function expression)은 function 표현에 비해 구문이 짧고  자신의 this, arguments, super 또는 new.target을 바인딩 하지 않습니다. 화살표 함수는 항상 익명입니다. 이  함수 표현은 메소드 함수가 아닌 곳에 가장 적합합니다. 그래서 생성자로서 사용할 수 없습니다.

+ +

{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}

+ +

구문

+ +

기본 구문

+ +
(param1, param2, …, paramN) => { statements }
+(param1, param2, …, paramN) => expression
+// 다음과 동일함:  => { return expression; }
+
+// 매개변수가 하나뿐인 경우 괄호는 선택사항:
+(singleParam) => { statements }
+singleParam => { statements }
+
+// 매개변수가 없는 함수는 괄호가 필요:
+() => { statements }
+ +

고급 구문

+ +
// 객체 리터럴 표현을 반환하기 위해서는 함수 본문(body)을 괄호 속에 넣음:
+params => ({foo: bar})
+
+// 나머지 매개변수기본 매개변수를 지원함
+(param1, param2, ...rest) => { statements }
+(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }
+
+// 매개변수 목록 내 구조분해할당도 지원됨
+var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
+f();  // 6
+
+ +

상세한 구문 예는 여기에서 볼 수 있습니다.

+ +

설명

+ +

Hacks 블로그 "ES6 In Depth: Arrow functions" 포스트 참조.

+ +

화살표 함수 도입에 영향을 준 두 요소: 보다 짧아진 함수 및  바인딩하지 않은 this.

+ +

짧은 함수

+ +

일부 함수 패턴에서는, 짧은 함수가 환영받습니다. 비교해 보세요:

+ +
var elements = [
+  'Hydrogen',
+  'Helium',
+  'Lithium',
+  'Beryllium'
+];
+
+// 이 문장은 배열을 반환함: [8, 6, 7, 9]
+elements.map(function(element) {
+  return element.length;
+});
+
+// 위의 일반적인 함수 표현은 아래 화살표 함수로 쓸 수 있다.
+elements.map((element) => {
+  return element.length;
+}); // [8, 6, 7, 9]
+
+// 파라미터가 하나만 있을 때는 주변 괄호를 생략할 수 있다.
+elements.map(element => {
+  return element.length;
+}); // [8, 6, 7, 9]
+
+// 화살표 함수의 유일한 문장이 'return'일 때 'return'과
+// 중괄호({})를 생략할 수 있다.
+elements.map(element => element.length); // [8, 6, 7, 9]
+
+// 이 경우 length 속성만 필요하므로 destructuring 매개변수를 사용할 수 있다.
+// 'length'는 우리가 얻고자 하는 속성에 해당하는 반면,
+// lengthFooBArX'는 변경 가능한 변수의 이름일 뿐이므로
+// 원하는 유효한 변수명으로 변경할 수 있다.
+elements.map(({ length: lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9]
+
+// destructuring 파라미터 할당도 아래와 같이 작성할 수 있습니다.
+// 이 예에서 정의한 객체내의 'length'에 값을 지정하지 않은 점에 주목하세요. 대신, "length" 변수의
+// 리터럴 이름은 우리가 해당 객체에서 꺼내오고 싶은 속성이름 자체로 사용됩니다.
+elements.map(({ length }) => length); // [8, 6, 7, 9] 
+ +

바인딩 되지 않은 this

+ +

화살표 함수가 나오기 전까지는, 모든 새로운 함수는, 어떻게 그 함수가 호출되는지에 따라  자신의 this 값을 정의했습니다:

+ + + +

이는 객체 지향 스타일로 프로그래밍할 때 별로 좋지않습니다.

+ +
function Person() {
+  // Person() 생성자는 `this`를 자신의 인스턴스로 정의.
+  this.age = 0;
+
+  setInterval(function growUp() {
+    // 비엄격 모드에서, growUp() 함수는 `this`를
+    // 전역 객체로 정의하고, 이는 Person() 생성자에
+    // 정의된 `this`와 다름.
+    this.age++;
+  }, 1000);
+}
+
+var p = new Person();
+ +

ECMAScript 3/5 에서는, 이 문제를 this 값을 폐쇄될 수 있는 (비전역) 변수에 할당하여 해결했습니다.

+ +
function Person() {
+  var that = this;
+  that.age = 0;
+
+  setInterval(function growUp() {
+    // 콜백은  `that` 변수를 참조하고 이것은 값이 기대한 객체이다.
+    that.age++;
+  }, 1000);
+}
+ +

이렇게 하는 대신에, 바인딩한 함수는 적절한 this 값이 growUp() 함수에 전달될 수 있도록 생성될 수 있습니다.

+ +

화살표 함수는 자신의 this가 없습니다.  대신 화살표 함수를 둘러싸는 렉시컬 범위(lexical scope)의 this가 사용됩니다; 화살표 함수는 일반 변수 조회 규칙(normal variable lookup rules)을 따릅니다. 때문에 현재 범위에서 존재하지 않는 this를 찾을 때, 화살표 함수는 바로 바깥 범위에서 this를 찾는것으로 검색을 끝내게 됩니다.

+ +

따라서 다음 코드에서 setInterval에 전달 된 함수 내부의 thissetInterval을 포함한 function의 this와 동일한 값을 갖습니다.

+ +
function Person(){
+  this.age = 0;
+
+  setInterval(() => {
+    this.age++; // |this|는 Person 객체를 참조
+  }, 1000);
+}
+
+var p = new Person();
+ +

엄격 모드와의 관계

+ +

this가 렉시컬(lexical, 정적)임을 감안하면, this에 관한 엄격 모드 규칙은 그냥 무시됩니다.

+ +
var f = () => { 'use strict'; return this; };
+f() === window; // 혹은 전역객체
+ +

엄격 모드의 나머지 규칙은 평소대로 적용합니다.

+ +

CORRECTION: START

+ +

NOTE: the previous statement seems false.

+ +

Strict mode should prevent creating global variables when assigning to an undeclared identifier in a function.

+ +

This code sample using Chrome 81 demonstrates that arrow functions allow the creation of global variables in such situations (both for a concise body and for a normal function body):

+ +
> f1 = x => { y = x; console.log(`x: ${x}, y: ${y}`); return x + 1; }
+x => { y = x; console.log(`x: ${x}, y: ${y}`); return x + 1; }
+
+> y
+VM51587:1 Uncaught ReferenceError: y is not defined
+    at <anonymous>:1:1
+(anonymous) @ VM51587:1
+
+> f1(3)
+VM51533:1 x: 3, y: 3
+4
+
+> y
+3
+
+> f2 = x => { 'use strict'; z = x; console.log(`x: ${x}, z: ${z}`); return x + 1; }
+x => { 'use strict'; z = x; console.log(`x: ${x}, z: ${z}`); return x + 1; }
+
+> z
+VM51757:1 Uncaught ReferenceError: z is not defined
+    at <anonymous>:1:1
+(anonymous) @ VM51757:1
+
+> f2(4)
+VM51712:1 Uncaught ReferenceError: z is not defined
+    at f2 (<anonymous>:1:29)
+    at <anonymous>:1:1
+f2 @ VM51712:1
+(anonymous) @ VM51800:1
+
+> f3 = x => (z1 = x + 1)
+x => (z1 = x + 1)
+
+> z1
+VM51891:1 Uncaught ReferenceError: z1 is not defined
+    at <anonymous>:1:1
+(anonymous) @ VM51891:1
+
+> f3(10)
+11
+
+> z1
+11
+
+ +

f2 illustrates that when explicitly setting the arrow function to apply strict mode, it does throw an error when attempting to assign an undeclared variable.

+ +

https://www.ecma-international.org/ecma-262/10.0/index.html#sec-strict-mode-code

+ +

https://www.ecma-international.org/ecma-262/10.0/index.html#sec-arrow-function-definitions-runtime-semantics-evaluation

+ +

CORRECTION: END

+ +

call 또는 apply를 통한 피호출

+ +

화살표 함수에서는 this가 바인딩되지 않았기 때문에, call() 또는 apply() 메서드는  인자만 전달 할 수 있습니다. this는 무시됩니다.

+ +
var adder = {
+  base : 1,
+
+  add : function(a) {
+    var f = v => v + this.base;
+    return f(a);
+  },
+
+  addThruCall: function(a) {
+    var f = v => v + this.base;
+    var b = {
+      base : 2
+    };
+
+    return f.call(b, a);
+  }
+};
+
+console.log(adder.add(1));         // 이는 2가 콘솔에 출력될 것임
+console.log(adder.addThruCall(1)); // 이도 2가 콘솔에 출력될 것임
+ +

바인딩 되지 않은 arguments

+ +

화살표 함수는 arguments 객체를 바인드 하지 않습니다.  때문에, arguments는  그저 둘러싸는 범위(scope) 내 이름에 대한 참조입니다.

+ +
var arguments = [1, 2, 3];
+var arr = () => arguments[0];
+
+arr(); // 1
+
+function foo(n) {
+  var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
+  return f();
+}
+
+foo(1); // 2
+ +

화살표 함수는 자신의 arguments 객체가 없지만, 대부분의 경우에 나머지 매개변수가 좋은 대안입니다:

+ +
function foo(n) {
+  var f = (...args) => args[0] + n;
+  return f(2);
+}
+
+foo(1); // 3
+ +

메소드로 사용되는 화살표 함수

+ +

이야기 했듯이, 화살표 함수 표현은 메소드 함수가 아닌 형태로 사용 할 수 있습니다. 메소드로 사용하려고 한면 무슨일이 발생하는지 봅시다.

+ +
'use strict';
+
+var obj = { // does not create a new scope
+  i: 10,
+  b: () => console.log(this.i, this),
+  c: function() {
+    console.log( this.i, this)
+  }
+}
+obj.b(); // prints undefined, Window {...} (or the global object)
+obj.c(); // prints 10, Object {...}
+
+ +

화살표 함수는 자신의 this를 가지고("bind" 바인드)있지 않습니다.{{jsxref("Object.defineProperty()")}}

+ +
'use strict';
+
+var obj = {
+  a: 10
+};
+
+Object.defineProperty(obj, 'b', {
+  get: () => {
+    console.log(this.a, typeof this.a, this); // undefined 'undefined' Window {...} (or the global object)
+    return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
+  }
+});
+ +

new 연산자 사용

+ +

화살표 함수는 생성자로서 사용될 수 없으며 new와 함께 사용하면 오류가 발생합니다.

+ +
var Foo = () => {};
+var foo = new Foo(); // TypeError: Foo is not a constructor
+ +

prototype 속성 사용

+ +

화살표 함수는 prototype 속성이 없습니다.

+ +
var Foo = () => {};
+console.log(Foo.prototype); // undefined
+ +

yield 키워드 사용

+ +

yield 키워드는 화살표 함수의 본문(그 안에 더 중첩된 함수 내에서 허용한 경우를 제외하고)에 사용될 수 없습니다. 그 결과, 화살표 함수는 생성기(generator)로서 사용될 수 없습니다.

+ +

함수 본문

+ +

화살표 함수는 "concise 바디"든 보통 "block 바디"든 하나를 가질 수 있습니다.

+ +
+

concise바디는 중괄호'{}'로 묶이지않은 한줄짜리 바디이고 block바디는 중괄호로 묶인 바디입니다. 보통 여러줄 쓸때 block바디를 사용합니다.

+
+ +

block바디는 자동으로 값을 반환하지 않습니다. return을 사용해서 값을 반환해야 합니다.

+ +
var func = x => x * x;                  // concise 바디, 생략된 "return" 여기서는 x * x
+var func = (x, y) => { return x + y; }; // block 바디, "return"이 필요
+
+ +

객체 리터럴 반환

+ +

간결한 구문 params => {object:literal}을 사용한 객체 리터럴 반환은 예상대로 작동하지 않음을 명심하세요:

+ +
var func = () => {  foo: 1  };
+// func() 호출은 undefined를 반환!
+
+var func = () => {  foo: function() {}  };
+// SyntaxError: function 문은 이름이 필요함
+ +

이는 중괄호({}) 안 코드가 일련의 문(즉 foo는 라벨처럼 취급됩니다, 객체 리터럴 내 키가 아니라)으로 파싱(parse, 구문 분석)되기 때문입니다.

+ +

객체 리터럴를 괄호로 감싸는 것을 기억하세요:

+ +
var func = () => ({ foo: 1 });
+ +

줄바꿈

+ +

화살표 함수는 파라메터와 화살표 사이에 개행 문자를 포함 할 수 없습니다.

+ +
var func = (a, b, c)
+           => 1;
+// SyntaxError: expected expression, got '=>'
+ +

하지만, 보기 좋은 코드를 유지하고 싶다면, 아래에 보는 것처럼 괄호나 개행을 둠으로써 이를 수정할 수 있습니다.

+ +
var func = (a, b, c) =>
+  1;
+
+var func = (a, b, c) => (
+  1
+);
+
+var func = (a, b, c) => {
+  return 1
+};
+
+var func = (
+  a,
+  b,
+  c
+) => 1;
+
+// SyntaxError가 발생하지 않습니다.
+ +

파싱순서

+ +

화살표 함수 내의 화살표는 연산자가 아닙니다. 그러나 화살표 함수는 평범한 함수와 비교했을 때 operator precedence와 다르게 반응하는 특별한 파싱룰을 가지고 있습니다.

+ +
let callback;
+
+callback = callback || function() {}; // ok
+
+callback = callback || () => {};
+// SyntaxError: invalid arrow-function arguments
+
+callback = callback || (() => {});    // ok
+
+ +

다른 예

+ +

기본 사용법

+ +
//  empty 화살표 함수는 undefined를 반환 
+let empty = () => {};
+
+(() => 'foobar')();
+// "foobar" 반환
+// (this is an Immediately Invoked Function Expression
+
+var simple = a => a > 15 ? 15 : a;
+simple(16); // 15
+simple(10); // 10
+
+let max = (a, b) => a > b ? a : b;
+
+// Easy array filtering, mapping, ...
+
+var arr = [5, 6, 13, 0, 1, 18, 23];
+
+var sum = arr.reduce((a, b) => a + b);
+// 66
+
+var even = arr.filter(v => v % 2 == 0);
+// [6, 0, 18]
+
+var double = arr.map(v => v * 2);
+// [10, 12, 26, 0, 2, 36, 46]
+
+// 더 간결한 promise 체인
+promise.then(a => {
+  // ...
+}).then(b => {
+  // ...
+});
+
+// 매개변수가 없는 경우에도 더 읽기 쉬움
+setTimeout( () => {
+  console.log('I happen sooner');
+  setTimeout( () => {
+    // deeper code
+    console.log('I happen later');
+  }, 1);
+}, 1);
+ +

스펙

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.functions.arrow_functions")}}

+ +

참조

+ + diff --git "a/files/ko/web/javascript/reference/functions/\354\225\240\353\241\234\354\232\260_\355\216\221\354\205\230/index.html" "b/files/ko/web/javascript/reference/functions/\354\225\240\353\241\234\354\232\260_\355\216\221\354\205\230/index.html" deleted file mode 100644 index 02dc0d55e4..0000000000 --- "a/files/ko/web/javascript/reference/functions/\354\225\240\353\241\234\354\232\260_\355\216\221\354\205\230/index.html" +++ /dev/null @@ -1,465 +0,0 @@ ---- -title: 화살표 함수 -slug: Web/JavaScript/Reference/Functions/애로우_펑션 -tags: - - ECMAScript6 - - Functions - - Intermediate - - JavaScript - - Reference -translation_of: Web/JavaScript/Reference/Functions/Arrow_functions ---- -
{{jsSidebar("Functions")}}
- -

화살표 함수 표현(arrow function expression)은 function 표현에 비해 구문이 짧고  자신의 this, arguments, super 또는 new.target을 바인딩 하지 않습니다. 화살표 함수는 항상 익명입니다. 이  함수 표현은 메소드 함수가 아닌 곳에 가장 적합합니다. 그래서 생성자로서 사용할 수 없습니다.

- -

{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}

- -

구문

- -

기본 구문

- -
(param1, param2, …, paramN) => { statements }
-(param1, param2, …, paramN) => expression
-// 다음과 동일함:  => { return expression; }
-
-// 매개변수가 하나뿐인 경우 괄호는 선택사항:
-(singleParam) => { statements }
-singleParam => { statements }
-
-// 매개변수가 없는 함수는 괄호가 필요:
-() => { statements }
- -

고급 구문

- -
// 객체 리터럴 표현을 반환하기 위해서는 함수 본문(body)을 괄호 속에 넣음:
-params => ({foo: bar})
-
-// 나머지 매개변수기본 매개변수를 지원함
-(param1, param2, ...rest) => { statements }
-(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }
-
-// 매개변수 목록 내 구조분해할당도 지원됨
-var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
-f();  // 6
-
- -

상세한 구문 예는 여기에서 볼 수 있습니다.

- -

설명

- -

Hacks 블로그 "ES6 In Depth: Arrow functions" 포스트 참조.

- -

화살표 함수 도입에 영향을 준 두 요소: 보다 짧아진 함수 및  바인딩하지 않은 this.

- -

짧은 함수

- -

일부 함수 패턴에서는, 짧은 함수가 환영받습니다. 비교해 보세요:

- -
var elements = [
-  'Hydrogen',
-  'Helium',
-  'Lithium',
-  'Beryllium'
-];
-
-// 이 문장은 배열을 반환함: [8, 6, 7, 9]
-elements.map(function(element) {
-  return element.length;
-});
-
-// 위의 일반적인 함수 표현은 아래 화살표 함수로 쓸 수 있다.
-elements.map((element) => {
-  return element.length;
-}); // [8, 6, 7, 9]
-
-// 파라미터가 하나만 있을 때는 주변 괄호를 생략할 수 있다.
-elements.map(element => {
-  return element.length;
-}); // [8, 6, 7, 9]
-
-// 화살표 함수의 유일한 문장이 'return'일 때 'return'과
-// 중괄호({})를 생략할 수 있다.
-elements.map(element => element.length); // [8, 6, 7, 9]
-
-// 이 경우 length 속성만 필요하므로 destructuring 매개변수를 사용할 수 있다.
-// 'length'는 우리가 얻고자 하는 속성에 해당하는 반면,
-// lengthFooBArX'는 변경 가능한 변수의 이름일 뿐이므로
-// 원하는 유효한 변수명으로 변경할 수 있다.
-elements.map(({ length: lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9]
-
-// destructuring 파라미터 할당도 아래와 같이 작성할 수 있습니다.
-// 이 예에서 정의한 객체내의 'length'에 값을 지정하지 않은 점에 주목하세요. 대신, "length" 변수의
-// 리터럴 이름은 우리가 해당 객체에서 꺼내오고 싶은 속성이름 자체로 사용됩니다.
-elements.map(({ length }) => length); // [8, 6, 7, 9] 
- -

바인딩 되지 않은 this

- -

화살표 함수가 나오기 전까지는, 모든 새로운 함수는, 어떻게 그 함수가 호출되는지에 따라  자신의 this 값을 정의했습니다:

- - - -

이는 객체 지향 스타일로 프로그래밍할 때 별로 좋지않습니다.

- -
function Person() {
-  // Person() 생성자는 `this`를 자신의 인스턴스로 정의.
-  this.age = 0;
-
-  setInterval(function growUp() {
-    // 비엄격 모드에서, growUp() 함수는 `this`를
-    // 전역 객체로 정의하고, 이는 Person() 생성자에
-    // 정의된 `this`와 다름.
-    this.age++;
-  }, 1000);
-}
-
-var p = new Person();
- -

ECMAScript 3/5 에서는, 이 문제를 this 값을 폐쇄될 수 있는 (비전역) 변수에 할당하여 해결했습니다.

- -
function Person() {
-  var that = this;
-  that.age = 0;
-
-  setInterval(function growUp() {
-    // 콜백은  `that` 변수를 참조하고 이것은 값이 기대한 객체이다.
-    that.age++;
-  }, 1000);
-}
- -

이렇게 하는 대신에, 바인딩한 함수는 적절한 this 값이 growUp() 함수에 전달될 수 있도록 생성될 수 있습니다.

- -

화살표 함수는 자신의 this가 없습니다.  대신 화살표 함수를 둘러싸는 렉시컬 범위(lexical scope)의 this가 사용됩니다; 화살표 함수는 일반 변수 조회 규칙(normal variable lookup rules)을 따릅니다. 때문에 현재 범위에서 존재하지 않는 this를 찾을 때, 화살표 함수는 바로 바깥 범위에서 this를 찾는것으로 검색을 끝내게 됩니다.

- -

따라서 다음 코드에서 setInterval에 전달 된 함수 내부의 thissetInterval을 포함한 function의 this와 동일한 값을 갖습니다.

- -
function Person(){
-  this.age = 0;
-
-  setInterval(() => {
-    this.age++; // |this|는 Person 객체를 참조
-  }, 1000);
-}
-
-var p = new Person();
- -

엄격 모드와의 관계

- -

this가 렉시컬(lexical, 정적)임을 감안하면, this에 관한 엄격 모드 규칙은 그냥 무시됩니다.

- -
var f = () => { 'use strict'; return this; };
-f() === window; // 혹은 전역객체
- -

엄격 모드의 나머지 규칙은 평소대로 적용합니다.

- -

CORRECTION: START

- -

NOTE: the previous statement seems false.

- -

Strict mode should prevent creating global variables when assigning to an undeclared identifier in a function.

- -

This code sample using Chrome 81 demonstrates that arrow functions allow the creation of global variables in such situations (both for a concise body and for a normal function body):

- -
> f1 = x => { y = x; console.log(`x: ${x}, y: ${y}`); return x + 1; }
-x => { y = x; console.log(`x: ${x}, y: ${y}`); return x + 1; }
-
-> y
-VM51587:1 Uncaught ReferenceError: y is not defined
-    at <anonymous>:1:1
-(anonymous) @ VM51587:1
-
-> f1(3)
-VM51533:1 x: 3, y: 3
-4
-
-> y
-3
-
-> f2 = x => { 'use strict'; z = x; console.log(`x: ${x}, z: ${z}`); return x + 1; }
-x => { 'use strict'; z = x; console.log(`x: ${x}, z: ${z}`); return x + 1; }
-
-> z
-VM51757:1 Uncaught ReferenceError: z is not defined
-    at <anonymous>:1:1
-(anonymous) @ VM51757:1
-
-> f2(4)
-VM51712:1 Uncaught ReferenceError: z is not defined
-    at f2 (<anonymous>:1:29)
-    at <anonymous>:1:1
-f2 @ VM51712:1
-(anonymous) @ VM51800:1
-
-> f3 = x => (z1 = x + 1)
-x => (z1 = x + 1)
-
-> z1
-VM51891:1 Uncaught ReferenceError: z1 is not defined
-    at <anonymous>:1:1
-(anonymous) @ VM51891:1
-
-> f3(10)
-11
-
-> z1
-11
-
- -

f2 illustrates that when explicitly setting the arrow function to apply strict mode, it does throw an error when attempting to assign an undeclared variable.

- -

https://www.ecma-international.org/ecma-262/10.0/index.html#sec-strict-mode-code

- -

https://www.ecma-international.org/ecma-262/10.0/index.html#sec-arrow-function-definitions-runtime-semantics-evaluation

- -

CORRECTION: END

- -

call 또는 apply를 통한 피호출

- -

화살표 함수에서는 this가 바인딩되지 않았기 때문에, call() 또는 apply() 메서드는  인자만 전달 할 수 있습니다. this는 무시됩니다.

- -
var adder = {
-  base : 1,
-
-  add : function(a) {
-    var f = v => v + this.base;
-    return f(a);
-  },
-
-  addThruCall: function(a) {
-    var f = v => v + this.base;
-    var b = {
-      base : 2
-    };
-
-    return f.call(b, a);
-  }
-};
-
-console.log(adder.add(1));         // 이는 2가 콘솔에 출력될 것임
-console.log(adder.addThruCall(1)); // 이도 2가 콘솔에 출력될 것임
- -

바인딩 되지 않은 arguments

- -

화살표 함수는 arguments 객체를 바인드 하지 않습니다.  때문에, arguments는  그저 둘러싸는 범위(scope) 내 이름에 대한 참조입니다.

- -
var arguments = [1, 2, 3];
-var arr = () => arguments[0];
-
-arr(); // 1
-
-function foo(n) {
-  var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
-  return f();
-}
-
-foo(1); // 2
- -

화살표 함수는 자신의 arguments 객체가 없지만, 대부분의 경우에 나머지 매개변수가 좋은 대안입니다:

- -
function foo(n) {
-  var f = (...args) => args[0] + n;
-  return f(2);
-}
-
-foo(1); // 3
- -

메소드로 사용되는 화살표 함수

- -

이야기 했듯이, 화살표 함수 표현은 메소드 함수가 아닌 형태로 사용 할 수 있습니다. 메소드로 사용하려고 한면 무슨일이 발생하는지 봅시다.

- -
'use strict';
-
-var obj = { // does not create a new scope
-  i: 10,
-  b: () => console.log(this.i, this),
-  c: function() {
-    console.log( this.i, this)
-  }
-}
-obj.b(); // prints undefined, Window {...} (or the global object)
-obj.c(); // prints 10, Object {...}
-
- -

화살표 함수는 자신의 this를 가지고("bind" 바인드)있지 않습니다.{{jsxref("Object.defineProperty()")}}

- -
'use strict';
-
-var obj = {
-  a: 10
-};
-
-Object.defineProperty(obj, 'b', {
-  get: () => {
-    console.log(this.a, typeof this.a, this); // undefined 'undefined' Window {...} (or the global object)
-    return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
-  }
-});
- -

new 연산자 사용

- -

화살표 함수는 생성자로서 사용될 수 없으며 new와 함께 사용하면 오류가 발생합니다.

- -
var Foo = () => {};
-var foo = new Foo(); // TypeError: Foo is not a constructor
- -

prototype 속성 사용

- -

화살표 함수는 prototype 속성이 없습니다.

- -
var Foo = () => {};
-console.log(Foo.prototype); // undefined
- -

yield 키워드 사용

- -

yield 키워드는 화살표 함수의 본문(그 안에 더 중첩된 함수 내에서 허용한 경우를 제외하고)에 사용될 수 없습니다. 그 결과, 화살표 함수는 생성기(generator)로서 사용될 수 없습니다.

- -

함수 본문

- -

화살표 함수는 "concise 바디"든 보통 "block 바디"든 하나를 가질 수 있습니다.

- -
-

concise바디는 중괄호'{}'로 묶이지않은 한줄짜리 바디이고 block바디는 중괄호로 묶인 바디입니다. 보통 여러줄 쓸때 block바디를 사용합니다.

-
- -

block바디는 자동으로 값을 반환하지 않습니다. return을 사용해서 값을 반환해야 합니다.

- -
var func = x => x * x;                  // concise 바디, 생략된 "return" 여기서는 x * x
-var func = (x, y) => { return x + y; }; // block 바디, "return"이 필요
-
- -

객체 리터럴 반환

- -

간결한 구문 params => {object:literal}을 사용한 객체 리터럴 반환은 예상대로 작동하지 않음을 명심하세요:

- -
var func = () => {  foo: 1  };
-// func() 호출은 undefined를 반환!
-
-var func = () => {  foo: function() {}  };
-// SyntaxError: function 문은 이름이 필요함
- -

이는 중괄호({}) 안 코드가 일련의 문(즉 foo는 라벨처럼 취급됩니다, 객체 리터럴 내 키가 아니라)으로 파싱(parse, 구문 분석)되기 때문입니다.

- -

객체 리터럴를 괄호로 감싸는 것을 기억하세요:

- -
var func = () => ({ foo: 1 });
- -

줄바꿈

- -

화살표 함수는 파라메터와 화살표 사이에 개행 문자를 포함 할 수 없습니다.

- -
var func = (a, b, c)
-           => 1;
-// SyntaxError: expected expression, got '=>'
- -

하지만, 보기 좋은 코드를 유지하고 싶다면, 아래에 보는 것처럼 괄호나 개행을 둠으로써 이를 수정할 수 있습니다.

- -
var func = (a, b, c) =>
-  1;
-
-var func = (a, b, c) => (
-  1
-);
-
-var func = (a, b, c) => {
-  return 1
-};
-
-var func = (
-  a,
-  b,
-  c
-) => 1;
-
-// SyntaxError가 발생하지 않습니다.
- -

파싱순서

- -

화살표 함수 내의 화살표는 연산자가 아닙니다. 그러나 화살표 함수는 평범한 함수와 비교했을 때 operator precedence와 다르게 반응하는 특별한 파싱룰을 가지고 있습니다.

- -
let callback;
-
-callback = callback || function() {}; // ok
-
-callback = callback || () => {};
-// SyntaxError: invalid arrow-function arguments
-
-callback = callback || (() => {});    // ok
-
- -

다른 예

- -

기본 사용법

- -
//  empty 화살표 함수는 undefined를 반환 
-let empty = () => {};
-
-(() => 'foobar')();
-// "foobar" 반환
-// (this is an Immediately Invoked Function Expression
-
-var simple = a => a > 15 ? 15 : a;
-simple(16); // 15
-simple(10); // 10
-
-let max = (a, b) => a > b ? a : b;
-
-// Easy array filtering, mapping, ...
-
-var arr = [5, 6, 13, 0, 1, 18, 23];
-
-var sum = arr.reduce((a, b) => a + b);
-// 66
-
-var even = arr.filter(v => v % 2 == 0);
-// [6, 0, 18]
-
-var double = arr.map(v => v * 2);
-// [10, 12, 26, 0, 2, 36, 46]
-
-// 더 간결한 promise 체인
-promise.then(a => {
-  // ...
-}).then(b => {
-  // ...
-});
-
-// 매개변수가 없는 경우에도 더 읽기 쉬움
-setTimeout( () => {
-  console.log('I happen sooner');
-  setTimeout( () => {
-    // deeper code
-    console.log('I happen later');
-  }, 1);
-}, 1);
- -

스펙

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}
- -

브라우저 호환성

- - - -

{{Compat("javascript.functions.arrow_functions")}}

- -

참조

- - diff --git a/files/ko/web/javascript/reference/global_objects/bigint/prototype/index.html b/files/ko/web/javascript/reference/global_objects/bigint/prototype/index.html deleted file mode 100644 index 6ba56eb37e..0000000000 --- a/files/ko/web/javascript/reference/global_objects/bigint/prototype/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: BigInt.prototype -slug: Web/JavaScript/Reference/Global_Objects/BigInt/prototype -tags: - - BigInt - - JavaScript - - Property - - Prototype - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/BigInt/prototype ---- -
{{JSRef}}
- -

BigInt.prototype 속성은 {{jsxref("BigInt")}} 생성자의 프로토타입을 나타냅니다.

- -

{{js_property_attributes(0, 0, 0)}}

- -

설명

- -

모든 {{jsxref("BigInt")}} 인스턴스는 BigInt.prototype을 상속합니다. BigInt 생성자의 프로토타입 객체를 변형해 모든 BigInt 인스턴스에 영향을 줄 수 있습니다.

- -

속성

- -
-
BigInt.prototype.constructor
-
이 객체의 인스턴스를 만들 때 사용한 함수를 반환합니다. 기본값은 {{jsxref("BigInt")}} 객체입니다.
-
- -

메서드

- -
-
BigInt.prototype.toLocaleString()
-
BigInt를 주어진 언어에 적합한 형태를 가진 문자열로 변환해 반환합니다. {{jsxref("Object.prototype.toLocaleString()")}} 메서드를 재정의합니다.
-
BigInt.prototype.toString()
-
BigInt의 값을 주어진 진수로 표현한 문자열을 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 재정의합니다.
-
BigInt.prototype.valueOf()
-
BigInt 객체의 원시 값 표현을 반환합니다. {{jsxref("Object.prototype.valueOf()")}} 메서드를 재정의합니다.
-
- -

명세

- - - - - - - - - - - - -
SpecificationStatus
BigInt.prototypeStage 3
- -

브라우저 호환성

- - - -

{{Compat("javascript.builtins.BigInt.prototype")}}

diff --git a/files/ko/web/javascript/reference/global_objects/boolean/prototype/index.html b/files/ko/web/javascript/reference/global_objects/boolean/prototype/index.html deleted file mode 100644 index 6e90207661..0000000000 --- a/files/ko/web/javascript/reference/global_objects/boolean/prototype/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Boolean.prototype -slug: Web/JavaScript/Reference/Global_Objects/Boolean/prototype -tags: - - Boolean - - JavaScript - - Property - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Boolean -translation_of_original: Web/JavaScript/Reference/Global_Objects/Boolean/prototype ---- -
{{JSRef}}
- -

Boolean.prototype 속성은 {{jsxref("Boolean")}} 생성자의 프로토타입을 나타냅니다.

- -
{{js_property_attributes(0, 0, 0)}}
- -
{{EmbedInteractiveExample("pages/js/boolean-constructor.html")}}
- - - -

설명

- -

{{jsxref("Boolean")}} 인스턴스는 Boolean.prototype을 상속받습니다. 생성자의 프로토타입 객체를 사용해 모든 Boolean 인스턴스에 속성이나 메서드를 추가할 수 있습니다.

- -

속성

- -
-
Boolean.prototype.constructor
-
인스턴스의 프로토타입을 생성한 함수를 반환합니다. 기본값은 {{jsxref("Boolean")}} 함수입니다.
-
- -

메서드

- -
-
{{jsxref("Boolean.prototype.toSource()")}} {{non-standard_inline}}
-
{{jsxref("Boolean")}} 객체의 소스를 포함한 문자열을 반환합니다. 반환 문자열을 사용해 동일한 객체를 생성할 수 있습니다. {{jsxref("Object.prototype.toSource()")}} 메서드를 재정의합니다.
-
{{jsxref("Boolean.prototype.toString()")}}
-
객체의 값에 따라 문자열 "true" 또는 "false"를 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 재정의합니다.
-
{{jsxref("Boolean.prototype.valueOf()")}}
-
{{jsxref("Boolean")}} 객체의 원시 값을 반환합니다. {{jsxref("Object.prototype.valueOf()")}} 메서드를 재정의합니다.
-
- -

명세

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.6.3.1', 'Boolean.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-boolean.prototype', 'Boolean.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-boolean.prototype', 'Boolean.prototype')}}{{Spec2('ESDraft')}} 
- -

브라우저 호환성

- - - -

{{Compat("javascript.builtins.Boolean.prototype")}}

diff --git a/files/ko/web/javascript/reference/global_objects/date/prototype/index.html b/files/ko/web/javascript/reference/global_objects/date/prototype/index.html deleted file mode 100644 index 06e1bba5f7..0000000000 --- a/files/ko/web/javascript/reference/global_objects/date/prototype/index.html +++ /dev/null @@ -1,183 +0,0 @@ ---- -title: Date.prototype -slug: Web/JavaScript/Reference/Global_Objects/Date/prototype -tags: - - Date - - JavaScript - - Property - - Prototype - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Date -translation_of_original: Web/JavaScript/Reference/Global_Objects/Date/prototype ---- -
{{JSRef}}
- -

Date.prototype 속성은 {{jsxref("Date")}} 생성자의 프로토타입을 나타냅니다.

- -
{{js_property_attributes(0, 0, 1)}}
- -

설명

- -

JavaScript {{jsxref("Date")}} 인스턴스는 Date.prototype을 상속합니다. 생성자의 프로토타입을 변경해 모든 Date 인스턴스의 속성과 메서드를 수정할 수 있습니다.

- -

2000년대 달력과의 호환성을 위해 연도는 언제나 완전하게 네 자리 숫자로 작성해야 합니다. 즉 98 대신 1998이 올바른 작성법입니다. Date는 완전한 연도 설정에 도움이 될 {{jsxref("Date.prototype.getFullYear()", "getFullYear()")}}, {{jsxref("Date.prototype.setFullYear()", "setFullYear()")}}, {{jsxref("Date.prototype.getUTCFullYear()", "getUTCFullYear()")}}, {{jsxref("Date.prototype.setUTCFullYear()", "setUTCFullYear()")}} 메서드를 가지고 있습니다.

- -

ECMAScript 6부터 Date.prototype은 {{jsxref("Date")}} 인스턴스가 아닌 평범한 객체입니다.

- -

속성

- -
-
Date.prototype.constructor
-
인스턴스 생성에 사용한 생성자를 반환합니다. 기본값은 {{jsxref("Date")}}입니다.
-
- -

메서드

- -

접근자

- -
-
{{jsxref("Date.prototype.getDate()")}}
-
주어진 날짜의 일(1-31)을 현지 시간에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getDay()")}}
-
주어진 날짜의 요일(0-6)을 현지 시간에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getFullYear()")}}
-
주어진 날짜의 연도(4자리 수)를 현지 시간에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getHours()")}}
-
주어진 날짜의 시(0-23)를 현지 시간에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getMilliseconds()")}}
-
주어진 날짜의 밀리초(0-999)를 현지 시간에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getMinutes()")}}
-
주어진 날짜의 분(0-59)을 현지 시간에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getMonth()")}}
-
주어진 날짜의 월(0-11)을 현지 시간에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getSeconds()")}}
-
주어진 날짜의 초(0-59)를 현지 시간에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getTime()")}}
-
주어진 날짜와 1970년 1월 1일 0시 0분(UTC)의 차이를 밀리초로 반환합니다.
-
{{jsxref("Date.prototype.getTimezoneOffset()")}}
-
현재 로케일의 시간대 차이를 분으로 환산해 반환합니다.
-
{{jsxref("Date.prototype.getUTCDate()")}}
-
주어진 날짜의 일(1-31)을 UTC에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getUTCDay()")}}
-
주어진 날짜의 요일(0-6)을 UTC에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getUTCFullYear()")}}
-
주어진 날짜의 연도(4자리 수)를 UTC에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getUTCHours()")}}
-
주어진 날짜의 시(0-23)를 UTC에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getUTCMilliseconds()")}}
-
주어진 날짜의 밀리초(0-999)를 UTC에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getUTCMinutes()")}}
-
주어진 날짜의 분(0-59)을 UTC에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getUTCMonth()")}}
-
주어진 날짜의 월(0-11)을 UTC에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getUTCSeconds()")}}
-
주어진 날짜의 초(0-59)를 UTC에 맞춰 반환합니다.
-
{{jsxref("Date.prototype.getYear()")}} {{deprecated_inline}}
-
주어진 날짜의 연도(주로 두세자리 숫자)를 현지 시간에 맞춰 반환합니다. {{jsxref("Date.prototype.getFullYear()", "getFullYear()")}}를 사용하세요.
-
- -

설정자

- -
-
{{jsxref("Date.prototype.setDate()")}}
-
Sets the day of the month for a specified date according to local time.
-
{{jsxref("Date.prototype.setFullYear()")}}
-
Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to local time.
-
{{jsxref("Date.prototype.setHours()")}}
-
Sets the hours for a specified date according to local time.
-
{{jsxref("Date.prototype.setMilliseconds()")}}
-
Sets the milliseconds for a specified date according to local time.
-
{{jsxref("Date.prototype.setMinutes()")}}
-
Sets the minutes for a specified date according to local time.
-
{{jsxref("Date.prototype.setMonth()")}}
-
Sets the month for a specified date according to local time.
-
{{jsxref("Date.prototype.setSeconds()")}}
-
Sets the seconds for a specified date according to local time.
-
{{jsxref("Date.prototype.setTime()")}}
-
Sets the {{jsxref("Date")}} object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC, allowing for negative numbers for times prior.
-
{{jsxref("Date.prototype.setUTCDate()")}}
-
Sets the day of the month for a specified date according to universal time.
-
{{jsxref("Date.prototype.setUTCFullYear()")}}
-
Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to universal time.
-
{{jsxref("Date.prototype.setUTCHours()")}}
-
Sets the hour for a specified date according to universal time.
-
{{jsxref("Date.prototype.setUTCMilliseconds()")}}
-
Sets the milliseconds for a specified date according to universal time.
-
{{jsxref("Date.prototype.setUTCMinutes()")}}
-
Sets the minutes for a specified date according to universal time.
-
{{jsxref("Date.prototype.setUTCMonth()")}}
-
Sets the month for a specified date according to universal time.
-
{{jsxref("Date.prototype.setUTCSeconds()")}}
-
Sets the seconds for a specified date according to universal time.
-
{{jsxref("Date.prototype.setYear()")}} {{deprecated_inline}}
-
Sets the year (usually 2-3 digits) for a specified date according to local time. Use {{jsxref("Date.prototype.setFullYear()", "setFullYear()")}} instead.
-
- -

변환 접근자

- -
-
{{jsxref("Date.prototype.toDateString()")}}
-
Returns the "date" portion of the {{jsxref("Date")}} as a human-readable string like 'Thu Apr 12 2018'
-
{{jsxref("Date.prototype.toISOString()")}}
-
Converts a date to a string following the ISO 8601 Extended Format.
-
{{jsxref("Date.prototype.toJSON()")}}
-
Returns a string representing the {{jsxref("Date")}} using {{jsxref("Date.prototype.toISOString()", "toISOString()")}}. Intended for use by {{jsxref("JSON.stringify()")}}.
-
{{jsxref("Date.prototype.toGMTString()")}} {{deprecated_inline}}
-
Returns a string representing the {{jsxref("Date")}} based on the GMT (UT) time zone. Use {{jsxref("Date.prototype.toUTCString()", "toUTCString()")}} instead.
-
{{jsxref("Date.prototype.toLocaleDateString()")}}
-
Returns a string with a locality sensitive representation of the date portion of this date based on system settings.
-
{{jsxref("Date.prototype.toLocaleFormat()")}} {{non-standard_inline}}
-
Converts a date to a string, using a format string.
-
{{jsxref("Date.prototype.toLocaleString()")}}
-
Returns a string with a locality sensitive representation of this date. Overrides the {{jsxref("Object.prototype.toLocaleString()")}} method.
-
{{jsxref("Date.prototype.toLocaleTimeString()")}}
-
Returns a string with a locality sensitive representation of the time portion of this date based on system settings.
-
{{jsxref("Date.prototype.toSource()")}} {{non-standard_inline}}
-
Returns a string representing the source for an equivalent {{jsxref("Date")}} object; you can use this value to create a new object. Overrides the {{jsxref("Object.prototype.toSource()")}} method.
-
{{jsxref("Date.prototype.toString()")}}
-
Returns a string representing the specified {{jsxref("Date")}} object. Overrides the {{jsxref("Object.prototype.toString()")}} method.
-
{{jsxref("Date.prototype.toTimeString()")}}
-
Returns the "time" portion of the {{jsxref("Date")}} as a human-readable string.
-
{{jsxref("Date.prototype.toUTCString()")}}
-
Converts a date to a string using the UTC timezone.
-
{{jsxref("Date.prototype.valueOf()")}}
-
Returns the primitive value of a {{jsxref("Date")}} object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.
-
- -

명세

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.9.5', 'Date.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-the-date-prototype-object', 'Date.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-the-date-prototype-object', 'Date.prototype')}}{{Spec2('ESDraft')}} 
- -

브라우저 호환성

- - - -

{{Compat("javascript.builtins.Date.prototype")}}

diff --git a/files/ko/web/javascript/reference/global_objects/internalerror/prototype/index.html b/files/ko/web/javascript/reference/global_objects/internalerror/prototype/index.html deleted file mode 100644 index 6e13afb6db..0000000000 --- a/files/ko/web/javascript/reference/global_objects/internalerror/prototype/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: InternalError.prototype -slug: Web/JavaScript/Reference/Global_Objects/InternalError/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/InternalError -translation_of_original: Web/JavaScript/Reference/Global_Objects/InternalError/prototype ---- -
{{JSRef}} {{non-standard_header}}
- -

InternalError.prototype 속성은 {{jsxref("InternalError")}} 생성자의 프로토타입을 나타냅니다.

- -
{{js_property_attributes(0, 0, 0)}}
- -

설명

- -

모든 {{jsxref("InternalError")}} 인스턴스는 InternalError.prototype 으로부터 상속받습니다. 프로토타입은 모든 인스턴스에 속성이나 메소드를 추가하거나 하는 데에 사용할 수 있습니다.

- -

속성

- -
-
InternalError.prototype.constructor
-
인스턴스의 프로토타입을 생성하는 함수를 명시합니다. 
-
{{jsxref("Error.prototype.message", "InternalError.prototype.message")}}
-
에러 메시지. {{jsxref("Error")}} 로부터 상속받습니다. 
-
{{jsxref("Error.prototype.name", "InternalError.prototype.name")}}
-
에러명. {{jsxref("Error")}} 로부터 상속받습니다.
-
{{jsxref("Error.prototype.fileName", "InternalError.prototype.fileName")}}
-
에러를 발생시킨 파일의 경로. {{jsxref("Error")}} 로부터 상속받습니다.
-
{{jsxref("Error.prototype.lineNumber", "InternalError.prototype.lineNumber")}}
-
에러를 발생시킨 파일의 라인 넘버. {{jsxref("Error")}} 로부터 상속받습니다.
-
{{jsxref("Error.prototype.columnNumber", "InternalError.prototype.columnNumber")}}
-
에러를 발생 시킨 라인의 컬럼 넘버. {{jsxref("Error")}} 로부터 상속받습니다.
-
{{jsxref("Error.prototype.stack", "InternalError.prototype.stack")}}
-
스택 트레이스. {{jsxref("Error")}} 로부터 상속받습니다. 
-
- -

메소드

- -

비록 {{jsxref("InternalError")}}의 프로토타입 객체는 고유의 메소드를 가지고 있지는 않습니다. 하지만, {{jsxref("InternalError")}} 인스턴스는 프로토타입 체인을 통해 몇 가지의 메소드를 상속 받습니다.

- -

스펙

- -

Not part of any specifications.

- -

브라우저 호환성

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

참조

- - diff --git a/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html b/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html deleted file mode 100644 index 2f1b031b39..0000000000 --- a/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: Intl.DateTimeFormat.prototype -slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/prototype -tags: - - DateTimeFormat - - Internationalization - - Intl - - JavaScript - - Property - - Prototype - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat -translation_of_original: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/prototype ---- -
{{JSRef}}
- -

Intl.DateTimeFormat.prototype 속성은 {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} 생성자의 프로토타입을 나타냅니다.

- -
{{js_property_attributes(0, 0, 0)}}
- -

설명

- -

Intl.DateTimeFormat 인스턴스에 대한 설명은 {{jsxref("DateTimeFormat")}} 문서를 참고하세요.

- -

{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} 인스턴스는 Intl.DateTimeFormat.prototype을 상속합니다. 프로토타입 객체를 변경하면 모든 {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} 인스턴스가 영향을 받습니다.

- -

속성

- -
-
Intl.DateTimeFormat.prototype.constructor
-
{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}}에 대한 참조입니다.
-
- -

메서드

- -
-
{{jsxref("DateTimeFormat.format", "Intl.DateTimeFormat.prototype.format()")}}
-
주어진 날짜에 {{jsxref("DateTimeFormat")}} 객체의 로케일과 서식 설정을 적용해 반환합니다.
-
- -
-
{{jsxref("DateTimeFormat.formatToParts", "Intl.DateTimeFormat.prototype.formatToParts()")}}
-
서식을 적용한 날짜 문자열의 각 부분을 객체로 표현해서 {{jsxref("Array")}}로 반환합니다. 반환 값은 로케일별 커스텀 서식에 사용할 수 있습니다.
-
{{jsxref("DateTimeFormat.resolvedOptions", "Intl.DateTimeFormat.prototype.resolvedOptions()")}}
-
객체 인스턴스 생성 때 주어진 로케일과 서식 설정이 어떻게 반영되었나 나타내는 새로운 객체를 반환합니다.
-
- -

명세

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES Int 1.0', '#sec-12.2.1', 'Intl.DateTimeFormat.prototype')}}{{Spec2('ES Int 1.0')}}Initial definition.
{{SpecName('ES Int 2.0', '#sec-12.2.1', 'Intl.DateTimeFormat.prototype')}}{{Spec2('ES Int 2.0')}}
{{SpecName('ES Int Draft', '#sec-Intl.DateTimeFormat.prototype', 'Intl.DateTimeFormat.prototype')}}{{Spec2('ES Int Draft')}}
- -

브라우저 호환성

- -
- - -

{{Compat("javascript.builtins.Intl.DateTimeFormat.prototype")}}

-
- -

같이 보기

- - diff --git a/files/ko/web/javascript/reference/global_objects/intl/numberformat/prototype/index.html b/files/ko/web/javascript/reference/global_objects/intl/numberformat/prototype/index.html deleted file mode 100644 index fcbaa6c247..0000000000 --- a/files/ko/web/javascript/reference/global_objects/intl/numberformat/prototype/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Intl.NumberFormat.prototype -slug: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/prototype -tags: - - Internationalization - - Intl - - JavaScript - - NumberFormat - - Property - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat -translation_of_original: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/prototype ---- -
{{JSRef}}
- -

Intl.NumberFormat.prototype 속성은 {{jsxref("NumberFormat", "Intl.NumberFormat")}} 생성자의 프로토타입을 나타냅니다.

- -
{{js_property_attributes(0, 0, 0)}}
- -

설명

- -

Intl.NumberFormat 인스턴스에 대한 설명은 {{jsxref("NumberFormat")}} 문서를 참고하세요.

- -

{{jsxref("NumberFormat", "Intl.NumberFormat")}} 인스턴스는 Intl.NumberFormat.prototype을 상속합니다. 프로토타입 객체를 변형하면 모든 {{jsxref("NumberFormat", "Intl.NumberFormat")}} 인스턴스가 영향을 받습니다.

- -

속성

- -
-
Intl.NumberFormat.prototype.constructor
-
Intl.NumberFormat에 대한 참조입니다.
-
- -

메서드

- -
-
{{jsxref("NumberFormat.format", "Intl.NumberFormat.prototype.format()")}}
-
주어진 숫자에 {{jsxref("NumberFormat")}} 객체의 로케일과 서식 설정을 적용해 반환합니다.
-
- -
-
{{jsxref("NumberFormat.formatToParts", "Intl.NumberFormat.prototype.formatToParts()")}}
-
서식을 적용한 숫자의 각 부분을 객체로 표현해서 {{jsxref("Array")}}로 반환합니다. 반환 값은 로케일별 커스텀 서식에 사용할 수 있습니다.
-
{{jsxref("NumberFormat.resolvedOptions", "Intl.NumberFormat.prototype.resolvedOptions()")}}
-
객체 인스턴스 생성 때 주어진 로케일과 콜레이션 설정이 어떻게 반영되었나 나타내는 새로운 객체를 반환합니다.
-
- -

명세

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES Int 1.0', '#sec-11.2.1', 'Intl.NumberFormat.prototype')}}{{Spec2('ES Int 1.0')}}Initial definition.
{{SpecName('ES Int 2.0', '#sec-11.2.1', 'Intl.NumberFormat.prototype')}}{{Spec2('ES Int 2.0')}}
{{SpecName('ES Int Draft', '#sec-Intl.NumberFormat.prototype', 'Intl.NumberFormat.prototype')}}{{Spec2('ES Int Draft')}}
- -

브라우저 호환성

- -
- - -

{{Compat("javascript.builtins.Intl.NumberFormat.prototype")}}

-
- -

같이 보기

- - diff --git a/files/ko/web/javascript/reference/global_objects/map/prototype/index.html b/files/ko/web/javascript/reference/global_objects/map/prototype/index.html deleted file mode 100644 index 3445bf2847..0000000000 --- a/files/ko/web/javascript/reference/global_objects/map/prototype/index.html +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: Map.prototype -slug: Web/JavaScript/Reference/Global_Objects/Map/prototype -tags: - - ECMAScript 2015 - - JavaScript - - Map - - Property - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Map -translation_of_original: Web/JavaScript/Reference/Global_Objects/Map/prototype ---- -
{{JSRef}}
- -

Map.prototype property는 {{jsxref("Map")}}의 프로토 타입을 나타낸다.

- -
{{js_property_attributes(0,0,0)}}
- -

Description

- -

{{jsxref("Map")}} instance는 {{jsxref("Map.prototype")}}를 상속한다. Constructor의 프로토타입에 property와 method를 추가함으로써 모든 Map 인스턴스에서 사용 가능하게끔 만들 수 있다.

- -

Properties

- -
-
Map.prototype.constructor
-
인스턴스의 프로토타입을 만드는 함수를 반환한다. 이것 {{jsxref("Map")}} 함수의 기본 값이다.
-
{{jsxref("Map.prototype.size")}}
-
Map 객체에 들어있는 key/value pair의 수를 반환한다.
-
- -

Methods

- -
-
{{jsxref("Map.prototype.clear()")}}
-
Map 객체의 모든 key/value pair를 제거한다.
-
{{jsxref("Map.delete", "Map.prototype.delete(key)")}}
-
주어진 키(Key)와 해당되는 값(Value)를 제거하고 제거하기 전에 Map.prototype.has(key)가 반환했던 값을 반환한다. 그 후의 Map.prototype.has(key)는 false를 반환한다.
-
{{jsxref("Map.prototype.entries()")}}
-
Map 객체 안의 모든 요소들을 [key, value] 형태의 array 로 집어넣은 순서대로 가지고 있는 Iterator 객체를 반환한다.
-
{{jsxref("Map.forEach", "Map.prototype.forEach(callbackFn[, thisArg])")}}
-
Map 객체 안에 존재하는 각각의 key/value pair에 집어넣은 순서대로 callbackFn을 부른다. 만약 thisArg 매개변수가 제공되면, 이것이 각 callback의 this 값으로 사용된다.
-
{{jsxref("Map.get", "Map.prototype.get(key)")}}
-
주어진 키(Key)에 해당되는 값(value)을 반환하고, 만약 없으면 undefined를 반환한다.
-
{{jsxref("Map.has", "Map.prototype.has(key)")}}
-
Map 객체 안에 주어진 key/value pair가 있는지 검사하고 Boolean 값을 반환한다.
-
{{jsxref("Map.prototype.keys()")}}
-
Map 객체 안의 모든 키(Key)들을 집어넣은 순서대로 가지고 있는 Iterator 객체를 반환한다.
-
{{jsxref("Map.set", "Map.prototype.set(key, value)")}}
-
Map 객체에 주어진 키(Key)에 값(Value)를 집어넣고, Map 객체를 반환한다.
-
{{jsxref("Map.prototype.values()")}}
-
Map 객체 안의 모든 (Value)들을 집어넣은 순서대로 가지고 있는 Iterator 객체를 반환한다.
-
{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}
-
Map 객체 안의 모든 요소들을 [key, value] 형태의 array 로 집어넣은 순서대로 가지고 있는 Iterator 객체를 반환한다.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map.prototype', 'Map.prototype')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype', 'Map.prototype')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{Compat("javascript.builtins.Map.prototype")}}

- -

See also

- - diff --git a/files/ko/web/javascript/reference/global_objects/number/prototype/index.html b/files/ko/web/javascript/reference/global_objects/number/prototype/index.html deleted file mode 100644 index 2bf39d20f9..0000000000 --- a/files/ko/web/javascript/reference/global_objects/number/prototype/index.html +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: Number.prototype -slug: Web/JavaScript/Reference/Global_Objects/Number/prototype -tags: - - JavaScript - - Number - - Property - - Prototype - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Number -translation_of_original: Web/JavaScript/Reference/Global_Objects/Number/prototype ---- -
{{JSRef}}
- -

Number.prototype 속성은 {{jsxref("Number")}} 생성자의 프로토타입을 나타냅니다.

- -
{{js_property_attributes(0, 0, 0)}}
- -

설명

- -

모든 {{jsxref("Number")}} 인스턴스는 Number.prototype을 상속합니다. {{jsxref("Number")}} 생성자의 프로토타입 객체는 모든 {{jsxref( "Number")}} 인스턴스에 영향을 미치도록 수정할 수 있습니다.

- -

속성

- -
-
Number.prototype.constructor
-
이 객체의 인스턴스를 생성한 함수를 반환합니다. 기본적으로 {{jsxref("Number")}} 객체 입니다.
-
- -

메서드

- -
-
{{jsxref("Number.prototype.toExponential()")}}
-
숫자의 지수표기법 표현을 문자열로 반환합니다.
-
{{jsxref("Number.prototype.toFixed()")}}
-
숫자의 고정소수점 표현을 문자열로 반환합니다.
-
{{jsxref("Number.prototype.toLocaleString()")}}
-
숫자의 표현을 특정 언어에 맞춘 형식의 문자열로 반환합니다. {{jsxref("Object.prototype.toLocaleString()")}} 메서드를 오버라이드 합니다.
-
{{jsxref("Number.prototype.toPrecision()")}}
-
지정한 정밀도로 숫자를 나타내는 문자열을 반환합니다. 고정소수점 혹은 지수표기법으로 표현합니다.
-
{{jsxref("Number.prototype.toSource()")}} {{non-standard_inline}}
-
지정한 {{jsxref("Number")}} 객체를 나타내는 객체 리터럴을 반환합니다. 이 값을 사용하여 새 객체를 만들 수 있습니다. {{jsxref("Object.prototype.toSource()")}} 메서드를 오버라이드 합니다.
-
{{jsxref("Number.prototype.toString()")}}
-
지정된 기수(기본 10진수)로 지정된 객체를 문자열로 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 오버라이드 합니다.
-
{{jsxref("Number.prototype.valueOf()")}}
-
지정한 객체의 기본 자료형(primitive) 값을 반환합니다. {{jsxref("Object.prototype.valueOf()")}} 메서드를 오버라이드 합니다.
-
- -

명세

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.4', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-the-number-prototype-object', 'Number')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-the-number-prototype-object', 'Number')}}{{Spec2('ESDraft')}} 
- -

브라우저 호환성

- - - -

{{Compat("javascript.builtins.Number.prototype")}}

- -

같이 보기

- - diff --git a/files/ko/web/javascript/reference/global_objects/object/prototype/index.html b/files/ko/web/javascript/reference/global_objects/object/prototype/index.html deleted file mode 100644 index 8f7b08793f..0000000000 --- a/files/ko/web/javascript/reference/global_objects/object/prototype/index.html +++ /dev/null @@ -1,219 +0,0 @@ ---- -title: Object.prototype -slug: Web/JavaScript/Reference/Global_Objects/Object/prototype -tags: - - JavaScript - - Object - - Property - - Reference - - 프로토타입 -translation_of: Web/JavaScript/Reference/Global_Objects/Object -translation_of_original: Web/JavaScript/Reference/Global_Objects/Object/prototype ---- -
{{JSRef}}
- -

Object.prototype 속성은 {{jsxref("Object")}} 프로토타입(원형) 객체를
- 나타냅니다.

- -
{{js_property_attributes(0, 0, 0)}}
- -

설명

- -

JavaScript에서 거의 모든 객체는 {{jsxref("Object")}}의 인스턴스입니다. 일반적인 객체는 Object.prototype 에서 속성과 메서드를 상속받으며, 그 중 일부는 (오버라이드 등으로 인해) 숨겨질 수 있습니다. 그러나, 의도적으로 Object를 생성할 때 ({{jsxref("Object.create", "Object.create(null)")}} 처럼) 이를 피할 수도 있고, {{jsxref("Object.setPrototypeOf")}} 등을 통해 나중에 무효화할 수도 있습니다.

- -

Object 프로토타입에 가하는 변경은 프로토타입 체인을 통해, 더 아래쪽 체인에서 덮어 쓴 경우가 아니라면 모든 객체에서 관측할 수 있습니다. 이는 객체를 확장하거나 행동을 바꿀 수 있는 매우 강력하면서도 위험한 방법을 제공합니다.

- - - -

속성

- -
-
{{jsxref("Object.prototype.constructor")}}
-
객체의 프로토타입을 생성하는 함수를 지정합니다.
-
{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}
-
객체가 초기화될 때 프로토타입으로 사용된 객체를 가리킵니다.
-
{{jsxref("Object.prototype.__noSuchMethod__")}} {{obsolete_inline}}
-
정의되지 않은 객체 멤버가 메소드로서 호출될 때 실행되는 함수를 정의하는 데 쓰였지만 제거되었습니다.
-
{{jsxref("Object.prototype.count","Object.prototype.__count__")}} {{obsolete_inline}}
-
사용자 정의 객체 상에 직접 있는 열거가능 속성의 수를 반환하는 데 쓰였지만 제거되었습니다.
-
{{jsxref("Object.prototype.parent","Object.prototype.__parent__")}} {{obsolete_inline}}
-
객체 문맥을 가리키는 데 쓰였지만 제거되었습니다.
-
- -

메서드

- -
-
{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
함수를 속성에 연결합니다, 접근했을 때 그 함수를 실행해 그 결과값을 반환하는.
-
{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
함수를 속성에 연결합니다, 설정했을 때 그 속성을 수정하는 함수를 실행하는.
-
{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
{{jsxref("Object.prototype.__defineGetter__()", "__defineGetter__()")}} 메소드에 의해 지정된 속성과 관련된 함수를 반환합니다.
-
{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
{{jsxref("Object.prototype.__defineSetter__()", "__defineSetter__()")}} 메소드에 의해 지정된 속성과 관련된 함수를 반환합니다.
-
{{jsxref("Object.prototype.hasOwnProperty()")}}
-
객체가 지정된 속성을 프로토타입 체인을 통해 상속되지 않은 그 객체의 직접 속성으로 포함하는지를 나타내는 boolean을 반환합니다.
-
{{jsxref("Object.prototype.isPrototypeOf()")}}
-
지정된 객체가 이 메소드가 호출된 객체의 프로토타입 체인 내에 있는지를 나타내는 boolean을 반환합니다.
-
{{jsxref("Object.prototype.propertyIsEnumerable()")}}
-
내부 ECMAScript [[Enumerable]] attribute가 설정된 경우를 나타내는 boolean을 반환합니다.
-
{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}
-
이 메소드가 호출된 객체를 나타내는 객체 리터럴의 출처를 포함하는 문자열을 반환합니다; 새로운 객체를 만들기 위해 이 값을 쓸 수 있습니다.
-
{{jsxref("Object.prototype.toLocaleString()")}}
-
{{jsxref("Object.toString", "toString()")}}을 호출합니다.
-
{{jsxref("Object.prototype.toString()")}}
-
객체의 문자열 표현을 반환합니다.
-
{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}
-
객체 속성에서 감시점을 제거합니다.
-
{{jsxref("Object.prototype.valueOf()")}}
-
지정된 객체의 원시값을 반환합니다.
-
{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}
-
객체 속성에 감시점을 추가합니다.
-
{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}
-
지정된 객체의 문맥에서 JavaScript 코드 문자열을 평가하는 데 쓰였지만 제거되었습니다.
-
- -

예제

- -

Object.prototype의 기본 메서드를 변경할 때, 기존 조직의 앞 또는 후에 확장(extension) 을 포장하여 코드를 주입시키는 것을 고려하자. 예를 들어서, 이 (시험받지
- 않은) 코드는 내장된 로직 또는 어떤 다른 확장이 실행되기 전에 커스텀 로직을 전제조건적으로 실행시킬 것이다.

- -

함수가 호출되었을 때, 불러온 매개변수들은 배열과 같은 형태로 '변수' arguments에 보관된다. 예를 들어 myFn(a, b, c) 라는 함수를 부를 때, 이 함수 내부에 배열형태로 매개변수 (a, b, c) 를 담게 된다. prototype을 훅을 이용해 수정할 때, 함수에서 apply()를 호출하여 단순하게 this와 arguments(호출 상태)에 현재 동작을 전달하면 된다. 이 패턴은 Node.prototype, Function.prototype등 prototype에도 사용할 수 있다.

- -
var current = Object.prototype.valueOf;
-
-// 현재 설정한 "-prop-value" 속성은 cross-cutting 이고 
-// 항상 같은 prototype chain이 아니기 때문에, 이 Object.prototype을 바꾸고 싶다.
-Object.prototype.valueOf = function() {
-  if (this.hasOwnProperty('-prop-value')) {
-    return this['-prop-value'];
-  } else {
-    // 이 객체 내 속성(property)이 하나가 아니라면, 현재 동작을 재구성한 것으로부터
-    // 기본 동작으로 되돌리자(복구). 
-    // apply 동작은 다른 언어에서의 "super"와 유사하다.
-    // 비록 valueOf()가 매개변수를 받지못하더라도, 다른 훅에서 있을 것이다.
-    return current.apply(this, arguments);
-  }
-}
-
- -

JavaScript는 엄밀히 말해서 하위클래스(sub-class) 객체가 없기에, prototype은 객체 역할을 하는 특정 함수의 "기반 클래스" 객체를 만드는 유용한 차선책입니다. 예를 들어:

- -
var Person = function() {
-  this.canTalk = true;
-};
-
-Person.prototype.greet = function() {
-  if (this.canTalk) {
-    console.log('Hi, I am ' + this.name);
-  }
-};
-
-var Employee = function(name, title) {
-  Person.call(this);
-  this.name = name;
-  this.title = title;
-};
-
-Employee.prototype = Object.create(Person.prototype);
-Employee.prototype.constructor = Employee;
-
-Employee.prototype.greet = function() {
-  if (this.canTalk) {
-    console.log('Hi, I am ' + this.name + ', the ' + this.title);
-  }
-};
-
-var Customer = function(name) {
-  Person.call(this);
-  this.name = name;
-};
-
-Customer.prototype = Object.create(Person.prototype);
-Customer.prototype.constructor = Customer;
-
-var Mime = function(name) {
-  Person.call(this);
-  this.name = name;
-  this.canTalk = false;
-};
-
-Mime.prototype = Object.create(Person.prototype);
-Mime.prototype.constructor = Mime;
-
-var bob = new Employee('Bob', 'Builder');
-var joe = new Customer('Joe');
-var rg = new Employee('Red Green', 'Handyman');
-var mike = new Customer('Mike');
-var mime = new Mime('Mime');
-
-bob.greet();
-// Hi, I am Bob, the Builder
-
-joe.greet();
-// Hi, I am Joe
-
-rg.greet();
-// Hi, I am Red Green, the Handyman
-
-mike.greet();
-// Hi, I am Mike
-
-mime.greet();
-
- -

명세

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
스펙상태설명
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.0에서 구현됨.
{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ESDraft')}}
- -

브라우저 호환성

- -

{{Compat("javascript.builtins.Object.prototype")}}

- -

참조

- - - -
-
<dicword style="user-select: text;">Even though valueOf() doesn't take arguments, some other hook may.</dicword><dicword style="user-select: text;"><dicimg id="play" style="background-image: url(chrome-extension://bmbdcffdhebhecemcchbkfnjlmdiiepe/play.gif);"></dicimg> Eng<dicimg id="copy" style="background-image: url(chrome-extension://bmbdcffdhebhecemcchbkfnjlmdiiepe/copy.png);" title="copy"></dicimg></dicword>
-
-
-
-valueOf ()가 인수를받지 않더라도 다른 후크가있을 수 있습니다.
- -
-
- - - -
diff --git a/files/ko/web/javascript/reference/global_objects/promise/prototype/index.html b/files/ko/web/javascript/reference/global_objects/promise/prototype/index.html deleted file mode 100644 index 2e393d68d3..0000000000 --- a/files/ko/web/javascript/reference/global_objects/promise/prototype/index.html +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Promise.prototype -slug: Web/JavaScript/Reference/Global_Objects/Promise/prototype -tags: - - JavaScript - - Promise - - Property - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Promise -translation_of_original: Web/JavaScript/Reference/Global_Objects/Promise/prototype ---- -
{{JSRef}}
- -

Promise.prototype 속성은 {{jsxref("Promise")}} 생성자의 프로토타입을 나타냅니다.

- -
{{js_property_attributes(0,0,0)}}
- -

설명

- -

{{jsxref("Promise")}} 인스턴스는 {{jsxref("Promise.prototype")}}을 상속합니다. 모든 Promise 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있습니다.

- -

속성

- -
-
Promise.prototype.constructor
-
인스턴스의 프로토타입을 만드는 함수를 반환합니다. 기본값은 {{jsxref("Promise")}} 함수입니다.
-
- -

메서드

- -
-
{{jsxref("Promise.prototype.catch()")}}
-
프로미스(promise)에 거부 처리기 콜백을 추가하고 호출된 경우 콜백의 반환값 또는 프로미스가 대신 이행된 경우 그 원래 이행(fulfillment)값으로 결정하는(resolving) 새 프로미스를 반환합니다.
-
{{jsxref("Promise.prototype.then()")}}
-
프로미스에 이행 또는 거부 처리기를 추가하고 호출된 처리기의 반환값 또는 프로미스가 처리되지 않은 경우 그 원래 처리된(settled) 값으로 결정하는 새 프로미스를 반환합니다 (즉 관련 처리기 onFulfilled 또는 onRejectedundefined인 경우).
-
{{jsxref("Promise.prototype.finally()")}}
-
Appends a handler to the promise, and returns a new promise which is resolved when the original promise is resolved. The handler is called when the promise is settled, whether fulfilled or rejected.
-
- -

명세

- - - - - - - - - - - - - - - - - - - -
명세상태설명
{{SpecName('ES6', '#sec-promise.prototype', 'Promise.prototype')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-promise.prototype', 'Promise.prototype')}}{{Spec2('ESDraft')}} 
- -

브라우저 호환성

- - - -

{{Compat("javascript.builtins.Promise.prototype")}}

- -

같이 보기

- - diff --git a/files/ko/web/javascript/reference/global_objects/proxy/handler/apply/index.html b/files/ko/web/javascript/reference/global_objects/proxy/handler/apply/index.html deleted file mode 100644 index b4928da1d8..0000000000 --- a/files/ko/web/javascript/reference/global_objects/proxy/handler/apply/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: handler.apply() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply -tags: - - apply트랩 - - 트랩 - - 프록시 -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply ---- -
{{JSRef}}
- -

handler.apply() 메소드는 함수호출 시를 위한 트랩(trap)이다.

- -

문법

- -
var p = new Proxy(target, {
-  apply: function(target, thisArg, argumentsList) {
-  }
-});
-
- -

인자

- -

apply 메소드에는 다음과 같은 인자가 들어온다.. this는 handler를 가리킨다.

- -
-
target
-
대상이 되는 객체(함수)
-
thisArg
-
호출 시 바인딩 된 this
-
argumentsList
-
호출 시 전달된 인자목록.
-
- -

반환 값

- -

apply 메소드는 어떤 값이든 반환할 수 있다.

- -

설명

- -

handler.apply 메소드는 함수호출 시를 위한 트랩이다.

- -

가로채기

- -

이 트랩은 다음과 같은 것들을 가로챌 수 있다:

- - - -

기본(불변)조건

- -

handler.apply 메소드에 대한 특별히 지켜야 할 기본조건은 없다.

- -

예제

- -

다음의 코드는 함수 호출 시에 트랩을 건다.

- -
var p = new Proxy(function() {}, {
-  apply: function(target, thisArg, argumentsList) {
-    console.log('호출됨: ' + argumentsList.join(', '));
-    return argumentsList[0] + argumentsList[1] + argumentsList[2];
-  }
-});
-
-console.log(p(1, 2, 3)); // "호출됨: 1, 2, 3"
-                         // 6
-
- -

관련 명세

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist', '[[Call]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist', '[[Call]]')}}{{Spec2('ESDraft')}} 
- -

브라우저별 호환성

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop("18")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("18")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

관련 내용

- - diff --git a/files/ko/web/javascript/reference/global_objects/proxy/handler/index.html b/files/ko/web/javascript/reference/global_objects/proxy/handler/index.html deleted file mode 100644 index d153c621c6..0000000000 --- a/files/ko/web/javascript/reference/global_objects/proxy/handler/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Proxy handler -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler -tags: - - ECMAScript 2015 - - JavaScript - - Proxy -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy -translation_of_original: Web/JavaScript/Reference/Global_Objects/Proxy/handler ---- -
{{JSRef}}
- -

The proxy's handler object is a placeholder object which contains traps for {{jsxref("Proxy", "proxies", "", 1)}}.

- -

Methods

- -

All traps are optional. If a trap has not been defined, the default behavior is to forward the operation to the target.

- -
-
{{jsxref("Global_Objects/Proxy/handler/getPrototypeOf", "handler.getPrototypeOf()")}}
-
A trap for {{jsxref("Object.getPrototypeOf")}}.
-
{{jsxref("Global_Objects/Proxy/handler/setPrototypeOf", "handler.setPrototypeOf()")}}
-
A trap for {{jsxref("Object.setPrototypeOf")}}.
-
{{jsxref("Global_Objects/Proxy/handler/isExtensible", "handler.isExtensible()")}}
-
A trap for {{jsxref("Object.isExtensible")}}.
-
{{jsxref("Global_Objects/Proxy/handler/preventExtensions", "handler.preventExtensions()")}}
-
A trap for {{jsxref("Object.preventExtensions")}}.
-
{{jsxref("Global_Objects/Proxy/handler/getOwnPropertyDescriptor", "handler.getOwnPropertyDescriptor()")}}
-
A trap for {{jsxref("Object.getOwnPropertyDescriptor")}}.
-
{{jsxref("Global_Objects/Proxy/handler/defineProperty", "handler.defineProperty()")}}
-
A trap for {{jsxref("Object.defineProperty")}}.
-
{{jsxref("Global_Objects/Proxy/handler/has", "handler.has()")}}
-
A trap for the {{jsxref("Operators/in", "in")}} operator.
-
{{jsxref("Global_Objects/Proxy/handler/get", "handler.get()")}}
-
A trap for getting property values.
-
{{jsxref("Global_Objects/Proxy/handler/set", "handler.set()")}}
-
A trap for setting property values.
-
{{jsxref("Global_Objects/Proxy/handler/deleteProperty", "handler.deleteProperty()")}}
-
A trap for the {{jsxref("Operators/delete", "delete")}} operator.
-
{{jsxref("Global_Objects/Proxy/handler/ownKeys", "handler.ownKeys()")}}
-
A trap for {{jsxref("Object.getOwnPropertyNames")}} and {{jsxref("Object.getOwnPropertySymbols")}}.
-
{{jsxref("Global_Objects/Proxy/handler/apply", "handler.apply()")}}
-
A trap for a function call.
-
{{jsxref("Global_Objects/Proxy/handler/construct", "handler.construct()")}}
-
A trap for the {{jsxref("Operators/new", "new")}} operator.
-
- -

Some non-standard traps are obsolete and have been removed.

- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}{{Spec2('ESDraft')}}The enumerate handler has been removed.
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.Proxy.handler")}}

- -

See also

- - diff --git a/files/ko/web/javascript/reference/global_objects/proxy/proxy/apply/index.html b/files/ko/web/javascript/reference/global_objects/proxy/proxy/apply/index.html new file mode 100644 index 0000000000..b4928da1d8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/proxy/proxy/apply/index.html @@ -0,0 +1,154 @@ +--- +title: handler.apply() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply +tags: + - apply트랩 + - 트랩 + - 프록시 +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply +--- +
{{JSRef}}
+ +

handler.apply() 메소드는 함수호출 시를 위한 트랩(trap)이다.

+ +

문법

+ +
var p = new Proxy(target, {
+  apply: function(target, thisArg, argumentsList) {
+  }
+});
+
+ +

인자

+ +

apply 메소드에는 다음과 같은 인자가 들어온다.. this는 handler를 가리킨다.

+ +
+
target
+
대상이 되는 객체(함수)
+
thisArg
+
호출 시 바인딩 된 this
+
argumentsList
+
호출 시 전달된 인자목록.
+
+ +

반환 값

+ +

apply 메소드는 어떤 값이든 반환할 수 있다.

+ +

설명

+ +

handler.apply 메소드는 함수호출 시를 위한 트랩이다.

+ +

가로채기

+ +

이 트랩은 다음과 같은 것들을 가로챌 수 있다:

+ + + +

기본(불변)조건

+ +

handler.apply 메소드에 대한 특별히 지켜야 할 기본조건은 없다.

+ +

예제

+ +

다음의 코드는 함수 호출 시에 트랩을 건다.

+ +
var p = new Proxy(function() {}, {
+  apply: function(target, thisArg, argumentsList) {
+    console.log('호출됨: ' + argumentsList.join(', '));
+    return argumentsList[0] + argumentsList[1] + argumentsList[2];
+  }
+});
+
+console.log(p(1, 2, 3)); // "호출됨: 1, 2, 3"
+                         // 6
+
+ +

관련 명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist', '[[Call]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist', '[[Call]]')}}{{Spec2('ESDraft')}} 
+ +

브라우저별 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop("18")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("18")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

관련 내용

+ + diff --git a/files/ko/web/javascript/reference/global_objects/proxy/proxy/index.html b/files/ko/web/javascript/reference/global_objects/proxy/proxy/index.html new file mode 100644 index 0000000000..d153c621c6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/proxy/proxy/index.html @@ -0,0 +1,82 @@ +--- +title: Proxy handler +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler +tags: + - ECMAScript 2015 + - JavaScript + - Proxy +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy +translation_of_original: Web/JavaScript/Reference/Global_Objects/Proxy/handler +--- +
{{JSRef}}
+ +

The proxy's handler object is a placeholder object which contains traps for {{jsxref("Proxy", "proxies", "", 1)}}.

+ +

Methods

+ +

All traps are optional. If a trap has not been defined, the default behavior is to forward the operation to the target.

+ +
+
{{jsxref("Global_Objects/Proxy/handler/getPrototypeOf", "handler.getPrototypeOf()")}}
+
A trap for {{jsxref("Object.getPrototypeOf")}}.
+
{{jsxref("Global_Objects/Proxy/handler/setPrototypeOf", "handler.setPrototypeOf()")}}
+
A trap for {{jsxref("Object.setPrototypeOf")}}.
+
{{jsxref("Global_Objects/Proxy/handler/isExtensible", "handler.isExtensible()")}}
+
A trap for {{jsxref("Object.isExtensible")}}.
+
{{jsxref("Global_Objects/Proxy/handler/preventExtensions", "handler.preventExtensions()")}}
+
A trap for {{jsxref("Object.preventExtensions")}}.
+
{{jsxref("Global_Objects/Proxy/handler/getOwnPropertyDescriptor", "handler.getOwnPropertyDescriptor()")}}
+
A trap for {{jsxref("Object.getOwnPropertyDescriptor")}}.
+
{{jsxref("Global_Objects/Proxy/handler/defineProperty", "handler.defineProperty()")}}
+
A trap for {{jsxref("Object.defineProperty")}}.
+
{{jsxref("Global_Objects/Proxy/handler/has", "handler.has()")}}
+
A trap for the {{jsxref("Operators/in", "in")}} operator.
+
{{jsxref("Global_Objects/Proxy/handler/get", "handler.get()")}}
+
A trap for getting property values.
+
{{jsxref("Global_Objects/Proxy/handler/set", "handler.set()")}}
+
A trap for setting property values.
+
{{jsxref("Global_Objects/Proxy/handler/deleteProperty", "handler.deleteProperty()")}}
+
A trap for the {{jsxref("Operators/delete", "delete")}} operator.
+
{{jsxref("Global_Objects/Proxy/handler/ownKeys", "handler.ownKeys()")}}
+
A trap for {{jsxref("Object.getOwnPropertyNames")}} and {{jsxref("Object.getOwnPropertySymbols")}}.
+
{{jsxref("Global_Objects/Proxy/handler/apply", "handler.apply()")}}
+
A trap for a function call.
+
{{jsxref("Global_Objects/Proxy/handler/construct", "handler.construct()")}}
+
A trap for the {{jsxref("Operators/new", "new")}} operator.
+
+ +

Some non-standard traps are obsolete and have been removed.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}{{Spec2('ESDraft')}}The enumerate handler has been removed.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Proxy.handler")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/set/prototype/index.html b/files/ko/web/javascript/reference/global_objects/set/prototype/index.html deleted file mode 100644 index 8183d348a9..0000000000 --- a/files/ko/web/javascript/reference/global_objects/set/prototype/index.html +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: Set.prototype -slug: Web/JavaScript/Reference/Global_Objects/Set/prototype -tags: - - ECMAScript 2015 - - JavaScript - - Property - - Reference - - set -translation_of: Web/JavaScript/Reference/Global_Objects/Set -translation_of_original: Web/JavaScript/Reference/Global_Objects/Set/prototype ---- -
{{JSRef}}
- -

Set.prototype 속성은 {{jsxref("Set")}} 생성자의 프로토타입을 나타냅니다.

- -
{{js_property_attributes(0,0,0)}}
- -

설명

- -

{{jsxref("Set")}} 인스턴스는 {{jsxref("Set.prototype")}}에서 상속합니다. 모든 Set 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있습니다.

- -

속성

- -
-
Set.prototype.constructor
-
인스턴스의 프로토타입을 만든 함수를 반환합니다. 이는 기본으로 {{jsxref("Set")}} 함수입니다.
-
{{jsxref("Set.prototype.size")}}
-
Set 객체 내 값의 개수를 반환합니다.
-
- -

메서드

- -
-
{{jsxref("Set.add", "Set.prototype.add(value)")}}
-
Set 객체에 주어진 값을 갖는 새로운 요소를 추가합니다. Set 객체를 반환합니다.
-
{{jsxref("Set.prototype.clear()")}}
-
Set 객체에서 모든 요소를 제거합니다.
-
{{jsxref("Set.delete", "Set.prototype.delete(value)")}}
-
value와 관련된 요소를 제거하고 Set.prototype.has(value)가 이전에 반환했던 값을 반환합니다. Set.prototype.has(value)는 그 뒤에 false를 반환합니다.
-
{{jsxref("Set.prototype.entries()")}}
-
삽입 순으로 Set 객체 내 각 값에 대한 [value, value] 배열을 포함하는 새로운 Iterator 객체를 반환합니다. 이는 Map 객체와 비슷하게 유지되므로 여기서 각 항목은 그 keyvalue에 대해 같은 값을 갖습니다.
-
{{jsxref("Set.forEach", "Set.prototype.forEach(callbackFn[, thisArg])")}}
-
삽입 순으로 Set 객체 내에 있는 각 값에 대해 한 번 callbackFn을 호출합니다. thisArg 매개변수가 forEach에 제공된 경우, 이는 각 콜백에 대해 this 값으로 사용됩니다.
-
{{jsxref("Set.has", "Set.prototype.has(value)")}}
-
Set 객체 내 주어진 값을 갖는 요소가 있는지를 주장하는(asserting, 나타내는) boolean을 반환합니다.
-
{{jsxref("Set.prototype.keys()")}}
-
values() 함수와 같은 함수로 삽입 순으로 Set 객체 내 각 요소에 대한 값을 포함하는 새로운 Iterator 객체를 반환합니다.
-
{{jsxref("Set.prototype.values()")}}
-
삽입 순으로 Set 객체 내 각 요소에 대한 을 포함하는 새로운 Iterator 객체를 반환합니다.
-
{{jsxref("Set.prototype.@@iterator()", "Set.prototype[@@iterator]()")}}
-
삽입 순으로 Set 객체 내 각 요소에 대한 을 포함하는 새로운 Iterator 객체를 반환합니다.
-
- -

명세

- - - - - - - - - - - - - - - - - - - -
명세상태설명
{{SpecName('ES6', '#sec-set.prototype', 'Set.prototype')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-set.prototype', 'Set.prototype')}}{{Spec2('ESDraft')}} 
- -

브라우저 호환성

- - - -

{{Compat("javascript.builtins.Set.prototype")}}

- -

같이 보기

- - diff --git a/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html b/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html deleted file mode 100644 index 849b70c1c6..0000000000 --- a/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: SharedArrayBuffer.prototype -slug: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/prototype -tags: - - JavaScript - - SharedArrayBuffer - - TypedArrays - - 공유 메모리 - - 속성 -translation_of: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer -translation_of_original: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/prototype ---- -
{{JSRef}}
- -

SharedArrayBuffer.prototype 속성은 {{jsxref("SharedArrayBuffer")}} 객체를위한 프로토타입을 나타냅니다.

- -
{{js_property_attributes(0,0,0)}}
- -

설명

- -

SharedArrayBuffer 인스턴스는 SharedArrayBuffer.prototype 을 상속합니다. 모든 생성자와 마찬가지로, 생성자의 프로토타입 객체를 변경하여 모든 SharedArrayBuffer 인스턴스에 변화를 줄 수 있습니다.

- -

속성

- -
-
SharedArrayBuffer.prototype.constructor
-
객체의 프로토타입을 생성하는 함수를 지정합니다. 초기 값은 SharedArrayBuffer 생성자에 내장된 표준입니다.
-
{{jsxref("SharedArrayBuffer.prototype.byteLength")}} {{readonlyInline}}
-
배열의 바이트 크기입니다. 배열이 생성되고 수정이 불가할 때 지정됩니다. 읽기 전용입니다.
-
- -

메소드

- -
-
{{jsxref("SharedArrayBuffer.slice", "SharedArrayBuffer.prototype.slice(begin, end)")}}
-
begin 부터 end 까지의 모든 것을 포함하는 SharedArrayBuffer 바이트의 복사본을 컨텐츠로 갖는 새로운 SharedArrayBuffer 를 반환합니다. begin 또는 end 가 음수인 경우, 인덱스는 배열의 끝에서부터이고 반대인 경우 시작부터입니다.
-
- -

명세

- - - - - - - - - - - - - - -
명세상태코멘트
{{SpecName('ESDraft', '#sec-sharedarraybuffer.prototype', 'SharedArrayBuffer.prototype')}}{{Spec2('ESDraft')}}ES2017 에서 초기 정의.
- -

브라우저 호환성

- - - -

{{Compat("javascript.builtins.SharedArrayBuffer.prototype")}}

- -

함께 보기

- - diff --git a/files/ko/web/javascript/reference/global_objects/string/prototype/index.html b/files/ko/web/javascript/reference/global_objects/string/prototype/index.html deleted file mode 100644 index fa32999954..0000000000 --- a/files/ko/web/javascript/reference/global_objects/string/prototype/index.html +++ /dev/null @@ -1,219 +0,0 @@ ---- -title: String.prototype -slug: Web/JavaScript/Reference/Global_Objects/String/prototype -tags: - - JavaScript - - Property - - Prototype - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String -translation_of_original: Web/JavaScript/Reference/Global_Objects/String/prototype ---- -
{{JSRef("Global_Objects", "String")}}
- -

요약

- -

String.prototype 프라퍼티는 {{jsxref("Global_Objects/String", "String")}} 프로토타입 오브젝트를 표현하고 있습니다.

- -
{{js_property_attributes(0, 0, 0)}}
- -

설명

- -

모든 {{jsxref("Global_Objects/String", "String")}} 인스턴스들은 String.prototype를 상속합니다. String 프라퍼티 오브젝트를 변경하면, 그 변경은 모든 {{jsxref("Global_Objects/String", "String")}} 인스턴스들에 영향을 주게 됩니다.

- -

Properties

- -
-
String.prototype.constructor
-
오브젝트의 프로토타입을 생성하는 함수를 명세합니다.
-
{{jsxref("String.prototype.length")}}
-
문자열의 길이를 반영합니다.
-
N
-
N번째 위치에 있는 문자에 접근하기 위해 사용합니다.  N 은 0과 {{jsxref("String.length", "length")}}보다 작은 값 사이에 있는 양의 정수입니다. 이 퍼라퍼티들은 읽기 전용(read-only) 속성을 가지고 있습니다. 
-
- -

메서드

- -

HTML과 관련이 없는 메서드

- -
-
{{jsxref("String.prototype.charAt()")}}
-
문자열 내 특정 위치(index)에 있는 문자를 반환합니다.
-
{{jsxref("String.prototype.charCodeAt()")}}
-
문자열 내 주어진 위치(index)에 있는 문자의 유니코드 값을 반환합니다.
-
{{jsxref("String.prototype.codePointAt()")}} {{experimental_inline}}
-
주어진 위치에 있는 UTF-16으로 인코딩된 코드 포인터값인 음수가 아닌 정수값을 반환합니다. 
-
{{jsxref("String.prototype.concat()")}}
-
두 문자열의 문자를 합쳐서 새로운 문자열로 만든 다음, 그 새로운 문자열을 반환합니다. 
-
{{jsxref("String.prototype.includes()")}} {{experimental_inline}}
-
문자열 내에 찾고자 하는 문자열이 있는지를 확인합니다. 
-
{{jsxref("String.prototype.endsWith()")}} {{experimental_inline}}
-
문자열에서 특정 문자열로 끝나는지를 확인할 수 있습니다.
-
{{jsxref("String.prototype.indexOf()")}}
-
{{jsxref("Global_Objects/String", "String")}} 오브젝트에 있는 특정 값이 일치하는 첫 번째 인덱스 값을 반환하며, 일치하는 값이 없을 경우에는 -1을 반환합니다.
-
{{jsxref("String.prototype.lastIndexOf()")}}
-
String 오브젝트에서 fromIndex로부터 반대방향으로 찾기 시작하여 특정 값이 일치하는 마지막 인덱스를 반환합니다. 문자열에서 일치하는 특정 값이 없으면 -1을 리턴합니다.
-
{{jsxref("String.prototype.localeCompare()")}}
-
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
-
{{jsxref("String.prototype.match()")}}
-
Used to match a regular expression against a string.
-
{{jsxref("String.prototype.normalize()")}} {{experimental_inline}}
-
Returns the Unicode Normalization Form of the calling string value.
-
{{jsxref("String.prototype.quote()")}} {{obsolete_inline}}
-
Wraps the string in double quotes (""").
-
{{jsxref("String.prototype.repeat()")}} {{experimental_inline}}
-
Returns a string consisting of the elements of the object repeated the given times.
-
{{jsxref("String.prototype.replace()")}}
-
Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
-
{{jsxref("String.prototype.search()")}}
-
Executes the search for a match between a regular expression and a specified string.
-
{{jsxref("String.prototype.slice()")}}
-
Extracts a section of a string and returns a new string.
-
{{jsxref("String.prototype.split()")}}
-
Splits a {{jsxref("Global_Objects/String", "String")}} object into an array of strings by separating the string into substrings.
-
{{jsxref("String.prototype.startsWith()")}} {{experimental_inline}}
-
Determines whether a string begins with the characters of another string.
-
{{jsxref("String.prototype.substr()")}}
-
Returns the characters in a string beginning at the specified location through the specified number of characters.
-
{{jsxref("String.prototype.substring()")}}
-
Returns the characters in a string between two indexes into the string.
-
{{jsxref("String.prototype.toLocaleLowerCase()")}}
-
The characters within a string are converted to lower case while respecting the current locale. For most languages, this will return the same as {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}.
-
{{jsxref("String.prototype.toLocaleUpperCase()")}}
-
The characters within a string are converted to upper case while respecting the current locale. For most languages, this will return the same as {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}}.
-
{{jsxref("String.prototype.toLowerCase()")}}
-
Returns the calling string value converted to lower case.
-
{{jsxref("String.prototype.toSource()")}} {{non-standard_inline}}
-
Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the {{jsxref("Object.prototype.toSource()")}} method.
-
{{jsxref("String.prototype.toString()")}}
-
Returns a string representing the specified object. Overrides the {{jsxref("Object.prototype.toString()")}} method.
-
{{jsxref("String.prototype.toUpperCase()")}}
-
Returns the calling string value converted to uppercase.
-
{{jsxref("String.prototype.trim()")}}
-
Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.
-
{{jsxref("String.prototype.trimLeft()")}} {{non-standard_inline}}
-
Trims whitespace from the left side of the string.
-
{{jsxref("String.prototype.trimRight()")}} {{non-standard_inline}}
-
Trims whitespace from the right side of the string.
-
{{jsxref("String.prototype.valueOf()")}}
-
Returns the primitive value of the specified object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.
-
{{jsxref("String.prototype.@@iterator()", "String.prototype[@@iterator]()")}} {{experimental_inline}}
-
Returns a new Iterator object that iterates over the code points of a String value, returning each code point as a String value.
-
- -

HTML wrapper methods

- -

These methods are of limited use, as they provide only a subset of the available HTML tags and attributes.

- -
-
{{jsxref("String.prototype.big()")}} {{deprecated_inline}}
-
{{HTMLElement("big")}}
-
{{jsxref("String.prototype.blink()")}} {{deprecated_inline}}
-
{{HTMLElement("blink")}}
-
{{jsxref("String.prototype.bold()")}} {{deprecated_inline}}
-
{{HTMLElement("b")}}
-
{{jsxref("String.prototype.fixed()")}} {{deprecated_inline}}
-
{{HTMLElement("tt")}}
-
{{jsxref("String.prototype.fontcolor()")}} {{deprecated_inline}}
-
{{htmlattrxref("color", "font", "<font color=\"color\">")}}
-
{{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}
-
{{htmlattrxref("size", "font", "<font size=\"size\">")}}
-
{{jsxref("String.prototype.italics()")}} {{deprecated_inline}}
-
{{HTMLElement("i")}}
-
{{jsxref("String.prototype.link()")}}
-
{{htmlattrxref("href", "a", "<a href=\"rul\">")}} (link to URL)
-
{{jsxref("String.prototype.small()")}} {{deprecated_inline}}
-
{{HTMLElement("small")}}
-
{{jsxref("String.prototype.strike()")}} {{deprecated_inline}}
-
{{HTMLElement("strike")}}
-
{{jsxref("String.prototype.sub()")}} {{deprecated_inline}}
-
{{HTMLElement("sub")}}
-
{{jsxref("String.prototype.sup()")}} {{deprecated_inline}}
-
{{HTMLElement("sup")}}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.5.3.1', 'String.prototype')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype', 'String.prototype')}}{{Spec2('ES6')}}
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/ko/web/javascript/reference/global_objects/syntaxerror/prototype/index.html b/files/ko/web/javascript/reference/global_objects/syntaxerror/prototype/index.html deleted file mode 100644 index aa38e80799..0000000000 --- a/files/ko/web/javascript/reference/global_objects/syntaxerror/prototype/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: SyntaxError.prototype -slug: Web/JavaScript/Reference/Global_Objects/SyntaxError/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/SyntaxError -translation_of_original: Web/JavaScript/Reference/Global_Objects/SyntaxError/prototype ---- -
{{JSRef}}
- -

SyntaxError.prototype 속성은 {{jsxref("SyntaxError")}} 객체의 생성자 프로토타입을 표현합니다.

- -

설명

- -

모든 {{jsxref("SyntaxError")}} 인스턴스는 SyntaxError.prototype 객체로부터 상속 받습니다. 또한, 속성이나 메소드를 추가할 때 모든 인스턴스에 프로토타입을 사용 할 수 있습니다.

- -

속성

- -
-
SyntaxError.prototype.constructor
-
인스턴스의 프로토타입을 생성하는 함수를 명시합니다.
-
{{jsxref("Error.prototype.message", "SyntaxError.prototype.message")}}
-
에러 메시지. 비록 ECMA-262는  {{jsxref("SyntaxError")}} 가 고유의 message 속성을 제공해야 한다고 명시하고 있지만, SpiderMonkey 에서는, {{jsxref("Error.prototype.message")}}를 상속 받습니다. 
-
{{jsxref("Error.prototype.name", "SyntaxError.prototype.name")}}
-
에러명. {{jsxref("Error")}}로부터 상속 받습니다.
-
{{jsxref("Error.prototype.fileName", "SyntaxError.prototype.fileName")}}
-
에러를 발생시킨 파일의 경로. {{jsxref("Error")}}로부터 상속 받습니다.
-
{{jsxref("Error.prototype.lineNumber", "SyntaxError.prototype.lineNumber")}}
-
에러가 발생한 파일의 코드 라인 넘버. {{jsxref("Error")}}로부터 상속 받습니다.
-
{{jsxref("Error.prototype.columnNumber", "SyntaxError.prototype.columnNumber")}}
-
에러가 발생된 라인의 컬럼 넘버. {{jsxref("Error")}}로부터 상속 받습니다.
-
{{jsxref("Error.prototype.stack", "SyntaxError.prototype.stack")}}
-
스택 트레이스. {{jsxref("Error")}}로부터 상속 받습니다.
-
- -

메소드

- -

비록 {{jsxref("SyntaxError")}} 프로토타입 객체는 고유의 메소드를 가지고 있지는 않지만, {{jsxref("SyntaxError")}} 인스턴스는 몇 가지의 메소드를 프로토타입 체인을 통하여 상속 받습니다.

- -

스펙

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의.
{{SpecName('ES5.1', '#sec-15.11.7.6', 'NativeError.prototype')}}{{Spec2('ES5.1')}}NativeError.prototype로 정의.
{{SpecName('ES6', '#sec-nativeerror.prototype', 'NativeError.prototype')}}{{Spec2('ES6')}}NativeError.prototype로 정의.
{{SpecName('ESDraft', '#sec-nativeerror.prototype', 'NativeError.prototype')}}{{Spec2('ESDraft')}}NativeError.prototype로 정의.
- -

브라우저 호환성

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

참조

- - diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/prototype/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/prototype/index.html deleted file mode 100644 index 75f63010bf..0000000000 --- a/files/ko/web/javascript/reference/global_objects/typedarray/prototype/index.html +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: TypedArray.prototype -slug: Web/JavaScript/Reference/Global_Objects/TypedArray/prototype -tags: - - JavaScript - - Property - - TypedArray -translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray -translation_of_original: Web/JavaScript/Reference/Global_Objects/TypedArray/prototype ---- -
{{JSRef}}
- -

TypedArray.prototype 속성(property)은 {{jsxref("TypedArray")}} 생성자에 대한 프로토타입을 나타냅니다.

- -
{{js_property_attributes(0,0,0)}}
- -

설명

- -

{{jsxref("TypedArray")}} 인스턴스는 {{jsxref("TypedArray.prototype")}}을 상속합니다. 모든 TypedArray 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있으며, TypedArrayTypedArray 객체 유형 중 하나입니다.

- -

상속에 관한 자세한 정보를 위해 TypedArray에 대한 설명도 참조하세요.

- -

속성

- -
-
TypedArray.prototype.constructor
-
인스턴스의 프로토타입을 만든 함수를 반환합니다. 이는 기본으로 해당 TypedArray 객체 유형 함수 중 하나입니다.
-
{{jsxref("TypedArray.prototype.buffer")}} {{readonlyInline}}
-
형식화 배열에 의해 참조되는 {{jsxref("ArrayBuffer")}}를 반환합니다. 생성 시에 고정되기에 읽기 전용.
-
{{jsxref("TypedArray.prototype.byteLength")}} {{readonlyInline}}
-
{{jsxref("ArrayBuffer")}}의 시작점부터 형식화 배열의 길이(단위 바이트)를 반환합니다. 생성 시에 고정되기에 읽기 전용.
-
{{jsxref("TypedArray.prototype.byteOffset")}} {{readonlyInline}}
-
{{jsxref("ArrayBuffer")}}의 시작점부터 형식화 배열의 오프셋(단위 바이트)을 반환합니다. 생성 시에 고정되기에 읽기 전용.
-
{{jsxref("TypedArray.prototype.length")}} {{readonlyInline}}
-
형식화 배열 내 보유한 요소의 수를 반환합니다. 생성 시에 고정되기에 읽기 전용.
-
- -

메서드

- -
-
{{jsxref("TypedArray.prototype.copyWithin()")}}
-
배열 내부 일련의 배열 요소를 복사합니다. {{jsxref("Array.prototype.copyWithin()")}}도 참조.
-
{{jsxref("TypedArray.prototype.entries()")}}
-
배열 내 각 인덱스에 대한 키/값 쌍을 포함하는 새로운 Array Iterator 객체를 반환합니다. {{jsxref("Array.prototype.entries()")}}도 참조.
-
{{jsxref("TypedArray.prototype.every()")}}
-
배열의 모든 요소가 함수로 제공되는 테스트를 통과하는지를 테스트합니다. {{jsxref("Array.prototype.every()")}}도 참조.
-
{{jsxref("TypedArray.prototype.fill()")}}
-
시작 인덱스부터 끝 인덱스까지 배열의 모든 요소를 고정값으로 채웁니다. {{jsxref("Array.prototype.fill()")}}도 참조.
-
{{jsxref("TypedArray.prototype.filter()")}}
-
제공되는 필터링 함수가 true를 반환하는 이 배열의 모든 요소를 갖는 새로운 배열을 생성합니다. {{jsxref("Array.prototype.filter()")}}도 참조.
-
{{jsxref("TypedArray.prototype.find()")}}
-
배열 내 요소가 제공되는 테스트 함수를 만족하는 경우 배열 내 찾은 값 또는 못 찾은 경우 undefined를 반환합니다. {{jsxref("Array.prototype.find()")}}도 참조.
-
{{jsxref("TypedArray.prototype.findIndex()")}}
-
배열 내 요소가 제공되는 테스트 함수를 만족하는 경우 배열 내 찾은 인덱스 또는 못 찾은 경우 -1을 반환합니다. {{jsxref("Array.prototype.findIndex()")}}도 참조.
-
{{jsxref("TypedArray.prototype.forEach()")}}
-
배열 내 각 요소에 대해 함수를 호출합니다. {{jsxref("Array.prototype.forEach()")}}도 참조.
-
{{jsxref("TypedArray.prototype.includes()")}} {{experimental_inline}}
-
형식화 배열이 특정 요소를 포함하는지를 판단해, 적절히 true 또는 false를 반환합니다. {{jsxref("Array.prototype.includes()")}}도 참조.
-
{{jsxref("TypedArray.prototype.indexOf()")}}
-
지정된 값과 같은 배열 내부 요소의 첫(최소) 인덱스 또는 못 찾은 경우 -1을 반환합니다. {{jsxref("Array.prototype.indexOf()")}}도 참조.
-
{{jsxref("TypedArray.prototype.join()")}}
-
배열의 모든 요소를 문자열로 합칩니다. {{jsxref("Array.prototype.join()")}}도 참조.
-
{{jsxref("TypedArray.prototype.keys()")}}
-
배열의 각 인덱스에 대한 키를 포함하는 새로운 Array Iterator를 반환합니다. {{jsxref("Array.prototype.keys()")}}도 참조.
-
{{jsxref("TypedArray.prototype.lastIndexOf()")}}
-
지정된 값과 같은 배열 내부 요소의 끝(최대) 인덱스 또는 못 찾은 경우 -1을 반환합니다. {{jsxref("Array.prototype.lastIndexOf()")}}도 참조.
-
{{jsxref("TypedArray.prototype.map()")}}
-
이 배열의 모든 요소에 제공된 함수를 호출한 결과를 갖는 새로운 배열을 생성합니다. {{jsxref("Array.prototype.map()")}}도 참조.
-
{{jsxref("TypedArray.prototype.move()")}} {{non-standard_inline}} {{unimplemented_inline}}
-
{{jsxref("TypedArray.prototype.copyWithin()")}}의 이전 비표준 버전.
-
{{jsxref("TypedArray.prototype.reduce()")}}
-
누산기(accumulator) 및 배열의 각 값(좌에서 우로)에 대해 한 값으로 줄도록 함수를 적용합니다. {{jsxref("Array.prototype.reduce()")}}도 참조.
-
{{jsxref("TypedArray.prototype.reduceRight()")}}
-
누산기 및 배열의 각 값(우에서 좌로)에 대해 한 값으로 줄도록 함수를 적용합니다. {{jsxref("Array.prototype.reduceRight()")}}도 참조.
-
{{jsxref("TypedArray.prototype.reverse()")}}
-
배열 요소의 순서를 뒤집습니다 — 처음이 마지막이 되고 마지막이 처음이 됩니다. {{jsxref("Array.prototype.reverse()")}}도 참조.
-
{{jsxref("TypedArray.prototype.set()")}}
-
형식화 배열에 여러 값을 저장합니다, 지정된 배열에서 입력 값을 읽어.
-
{{jsxref("TypedArray.prototype.slice()")}}
-
배열의 한 부분을 추출하여 새로운 배열을 반환합니다. {{jsxref("Array.prototype.slice()")}}도 참조.
-
{{jsxref("TypedArray.prototype.some()")}}
-
이 배열의 적어도 한 요소가 제공된 테스트 함수를 만족하는 경우 true를 반환합니다. {{jsxref("Array.prototype.some()")}}도 참조.
-
{{jsxref("TypedArray.prototype.sort()")}}
-
배열의 요소를 적소에 정렬해 그 배열을 반환합니다. {{jsxref("Array.prototype.sort()")}}도 참조.
-
{{jsxref("TypedArray.prototype.subarray()")}}
-
주어진 시작 및 끝 요소 인덱스로부터 새로운 TypedArray를 반환합니다.
-
{{jsxref("TypedArray.prototype.values()")}}
-
배열의 각 인덱스에 대한 값을 포함하는 새로운 Array Iterator 객체를 반환합니다. {{jsxref("Array.prototype.values()")}}도 참조.
-
{{jsxref("TypedArray.prototype.toLocaleString()")}}
-
배열 및 그 요소를 나타내는 지역화된 문자열을 반환합니다. {{jsxref("Array.prototype.toLocaleString()")}}도 참조.
-
{{jsxref("TypedArray.prototype.toString()")}}
-
배열 및 그 요소를 나타내는 문자열을 반환합니다. {{jsxref("Array.prototype.toString()")}}도 참조.
-
{{jsxref("TypedArray.prototype.@@iterator()", "TypedArray.prototype[@@iterator]()")}}
-
배열의 각 인덱스에 대한 값을 포함하는 새로운 Array Iterator 객체를 반환합니다.
-
- -

스펙

- - - - - - - - - - - - - - - - - - - -
스펙상태설명
{{SpecName('ES6', '#sec-properties-of-the-%typedarrayprototype%-object', 'TypedArray prototype')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-properties-of-the-%typedarrayprototype%-object', 'TypedArray prototype')}}{{Spec2('ESDraft')}} 
- -

브라우저 호환성

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support7.0{{ CompatGeckoDesktop("2") }}1011.65.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.0{{CompatVersionUnknown}}{{ CompatGeckoMobile("2") }}1011.64.2
-
- -

참조

- - diff --git a/files/ko/web/javascript/reference/global_objects/weakmap/prototype/index.html b/files/ko/web/javascript/reference/global_objects/weakmap/prototype/index.html deleted file mode 100644 index fa2ad9691d..0000000000 --- a/files/ko/web/javascript/reference/global_objects/weakmap/prototype/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: WeakMap.prototype -slug: Web/JavaScript/Reference/Global_Objects/WeakMap/prototype -tags: - - ECMAScript6 - - JavaScript - - Property - - WeakMap -translation_of: Web/JavaScript/Reference/Global_Objects/WeakMap -translation_of_original: Web/JavaScript/Reference/Global_Objects/WeakMap/prototype ---- -
{{JSRef}}
- -

WeakMap.prototype 속성(property)은 {{jsxref("WeakMap")}} 생성자에 대한 프로토타입을 나타냅니다.

- -
{{js_property_attributes(0,0,0)}}
- -

설명

- -

{{jsxref("WeakMap")}} 인스턴스는 {{jsxref("WeakMap.prototype")}}에서 상속합니다. 모든 WeakMap 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있습니다.

- -

WeakMap.prototype은 그 자체로 그냥 평범한 객체입니다:

- -
Object.prototype.toString.call(WeakMap.prototype); // "[object Object]"
- -

속성

- -
-
WeakMap.prototype.constructor
-
인스턴스의 프로토타입을 생성한 함수를 반환합니다. 이는 기본으로 {{jsxref("WeakMap")}} 함수입니다.
-
- -

메서드

- -
-
{{jsxref("WeakMap.delete", "WeakMap.prototype.delete(key)")}}
-
key와 관련된 모든 값을 제거합니다. WeakMap.prototype.has(key)는 그 뒤에 false를 반환합니다.
-
{{jsxref("WeakMap.get", "WeakMap.prototype.get(key)")}}
-
key와 관련된 값 또는 관련 값이 없는 경우 undefined를 반환합니다.
-
{{jsxref("WeakMap.has", "WeakMap.prototype.has(key)")}}
-
WeakMap 객체 내 key와 관련된 값이 있는지 여부를 주장하는(asserting, 나타내는) boolean을 반환합니다.
-
{{jsxref("WeakMap.set", "WeakMap.prototype.set(key, value)")}}
-
WeakMap 객체 내 key에 대해 값을 설정합니다. WeakMap 객체를 반환합니다.
-
{{jsxref("WeakMap.prototype.clear()")}} {{obsolete_inline}}
-
WeakMap 객체에서 모든 키/값 쌍을 제거합니다. 메서드가 없는 WeakMap 객체를 캡슐화하여 .clear() 메서드가 있는 WeakMap 같은 객체 구현이 가능함을 주의하세요 ({{jsxref("WeakMap")}} 페이지 예 참조)
-
- -

스펙

- - - - - - - - - - - - - - - - - - - -
스펙상태설명
{{SpecName('ES6', '#sec-weakmap.prototype', 'WeakMap.prototype')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-weakmap.prototype', 'WeakMap.prototype')}}{{Spec2('ESDraft')}} 
- -

브라우저 호환성

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support36{{CompatGeckoDesktop("6.0")}}11237.1
Ordinary object{{CompatUnknown}}{{CompatGeckoDesktop("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("6.0")}}{{CompatNo}}{{CompatNo}}8
Ordinary object{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

참조

- - diff --git a/files/ko/web/javascript/reference/global_objects/weakset/prototype/index.html b/files/ko/web/javascript/reference/global_objects/weakset/prototype/index.html deleted file mode 100644 index 0c75408df5..0000000000 --- a/files/ko/web/javascript/reference/global_objects/weakset/prototype/index.html +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: WeakSet.prototype -slug: Web/JavaScript/Reference/Global_Objects/WeakSet/prototype -tags: - - ECMAScript6 - - JavaScript - - Property - - WeakSet -translation_of: Web/JavaScript/Reference/Global_Objects/WeakSet -translation_of_original: Web/JavaScript/Reference/Global_Objects/WeakSet/prototype ---- -
{{JSRef}}
- -

WeakSet.prototype 속성(property)은 {{jsxref("WeakSet")}} 생성자에 대한 프로토타입을 나타냅니다.

- -
{{js_property_attributes(0,0,0)}}
- -

설명

- -

{{jsxref("WeakSet")}} 인스턴스는 {{jsxref("WeakSet.prototype")}}에서 상속합니다. 모든 WeakSet 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있습니다.

- -

WeakSet.prototype은 그 자체로 그냥 평범한 객체입니다:

- -
Object.prototype.toString.call(WeakSet.prototype); // "[object Object]"
- -

속성

- -
-
WeakSet.prototype.constructor
-
인스턴스의 프로토타입을 생성한 함수를 반환합니다. 이는 기본으로 {{jsxref("WeakSet")}} 함수입니다.
-
- -

메서드

- -
-
{{jsxref("WeakSet.add", "WeakSet.prototype.add(value)")}}
-
WeakSet 객체에 주어진 값을 갖는 새로운 객체를 추가합니다.
-
{{jsxref("WeakSet.delete", "WeakSet.prototype.delete(value)")}}
-
value와 관련된 요소를 제거합니다. WeakSet.prototype.has(value)는 그 뒤에 false를 반환합니다.
-
{{jsxref("WeakSet.has", "WeakSet.prototype.has(value)")}}
-
WeakSet 객체 내 주어진 값을 갖는 요소가 존재하는 지 여부를 주장하는(asserting, 나타내는) boolean을 반환합니다.
-
{{jsxref("WeakSet.prototype.clear()")}} {{obsolete_inline}}
-
WeakSet 객체에서 모든 요소를 제거합니다.
-
- -

스펙

- - - - - - - - - - - - - - - - - - - -
스펙상태설명
{{SpecName('ES6', '#sec-weakset.prototype', 'WeakSet.prototype')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-weakset.prototype', 'WeakSet.prototype')}}{{Spec2('ESDraft')}} 
- -

브라우저 호환성

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support36{{ CompatGeckoDesktop(34) }}{{CompatNo}}23{{CompatNo}}
Ordinary object{{CompatUnknown}}{{CompatGeckoDesktop("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChrome for AndroidAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile(34) }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Ordinary object{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

참조

- - diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/global/prototype/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/global/prototype/index.html deleted file mode 100644 index c7c1c54bab..0000000000 --- a/files/ko/web/javascript/reference/global_objects/webassembly/global/prototype/index.html +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: WebAssembly.Global.prototype -slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Global -translation_of_original: Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/prototype ---- -
{{JSRef}}
- -

WebAssembly.Global.prototype 속성은 {{jsxref("WebAssembly.Global()")}} 생성자의 프로토 타입을 나타냅니다.

- -
{{js_property_attributes(0, 0, 0)}}
- -

Description

- -

모든 {{jsxref("WebAssembly.Global")}} 인스턴스는 Global.prototype에서 상속받습니다. {{jsxref("WebAssembly.Global()")}} 생성자의 프로토 타입 객체는 모든 {{jsxref( "WebAssembly.Global")}} 인스턴스에 영향을 미치도록 수정할 수 있습니다.

- -

Properties

- -
-
Global.prototype.constructor
-
이 객체의 인스턴스를 생성 한 함수를 돌려줍니다. 기본적으로 이것은 {{jsxref("WebAssembly.Global()")}} 생성자입니다.
-
Global.prototype[@@toStringTag]
-
@@toStringTag 속성의 초기 값은 String 값인 "WebAssembly.Global"입니다.
-
Global.prototype.value
-
전역 변수에 포함 된 값 - 전역 값을 직접 설정하고 가져 오는 데 사용할 수 있습니다.
-
- -

Methods

- -
-
Global.prototype.valueOf()
-
전역 변수에 포함 된 값을 반환하는 Old-style 메서드입니다.
-
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebAssembly JS', '#globals', 'WebAssembly.Global()')}}{{Spec2('WebAssembly JS')}}Initial draft definition.
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.WebAssembly.Global.prototype")}}

-
- -
- -
- -

See also

- - diff --git a/files/ko/web/javascript/reference/operators/arithmetic_operators/index.html b/files/ko/web/javascript/reference/operators/arithmetic_operators/index.html deleted file mode 100644 index 3e61415550..0000000000 --- a/files/ko/web/javascript/reference/operators/arithmetic_operators/index.html +++ /dev/null @@ -1,291 +0,0 @@ ---- -title: 산술 연산자 -slug: Web/JavaScript/Reference/Operators/Arithmetic_Operators -tags: - - JavaScript - - Operator - - Reference -translation_of: Web/JavaScript/Reference/Operators -translation_of_original: Web/JavaScript/Reference/Operators/Arithmetic_Operators ---- -
{{jsSidebar("Operators")}}
- -

산술 연산자는 숫자 값(리터럴 또는 변수)을 피연산자로 받아 하나의 숫자 값을 반환합니다. 표준 산술 연산자는 덧셈(+), 뺄셈(-), 곱셈(*), 나눗셈(/)입니다.

- -
{{EmbedInteractiveExample("pages/js/expressions-arithmetic.html")}}
- - - -

덧셈 (+)

- -

덧셈 연산자는 숫자 피연산자를 더한 값, 또는 문자열을 연결한 값을 생성합니다.

- -

구문

- -
연산자: x + y
-
- -

예제

- -
// Number + Number -> 합
-1 + 2 // 3
-
-// Boolean + Number -> 합
-true + 1 // 2
-
-// Boolean + Boolean -> 합
-false + false // 0
-
-// Number + String -> 연결
-5 + "foo" // "5foo"
-
-// String + Boolean -> 연결
-"foo" + false // "foofalse"
-
-// String + String -> 연결
-"foo" + "bar" // "foobar"
-
- -

뺄셈 (-)

- -

뺄셈 연산자는 두 개의 피연산자를 뺀 값을 생성합니다.

- -

구문

- -
연산자: x - y
-
- -

예제

- -
5 - 3 // 2
-3 - 5 // -2
-"foo" - 3 // NaN
- -

나눗셈 (/)

- -

나눗셈 연산자는 왼쪽 피연산자를 피제수로, 오른쪽 피연산자를 제수로 한 몫을 생성합니다.

- -

구문

- -
연산자: x / y
-
- -

예제

- -
1 / 2      // JavaScript에선 0.5
-1 / 2      // Java에선 0
-// (양쪽 피연산자 모두 명시적인 부동소수점 숫자가 아님)
-
-1.0 / 2.0  // JavaScript와 Java 둘 다 0.5
-
-2.0 / 0    // JavaScript에서 Infinity
-2.0 / 0.0  // 동일하게 Infinity
-2.0 / -0.0 // JavaScript에서 -Infinity
- -

곱셈 (*)

- -

곱셈 연산자는 두 연산자의 곱을 생성합니다.

- -

구문

- -
연산자: x * y
-
- -

예제

- -
2 * 2 // 4
--2 * 2 // -4
-Infinity * 0 // NaN
-Infinity * Infinity // Infinity
-"foo" * 2 // NaN
-
- -

나머지 (%)

- -

나머지 연산자는 왼쪽 피연산자를 오른쪽 피연산자로 나눴을 때의 나머지를 반환합니다. 결과는 항상 피제수의 부호를 따라갑니다.

- -

구문

- -
연산자: var1 % var2
-
- -

예제

- -
12 % 5 // 2
--1 % 2 // -1
-NaN % 2 // NaN
-1 % 2 // 1
-2 % 3 // 2
--4 % 2 // -0
-5.5 % 2 // 1.5
-
- -

거듭제곱 (**)

- -

거듭제곱 연산자는 첫 번째 피연산자를 밑으로, 두 번째 피연산자를 지수로 한 값을 생성합니다. 즉, var1var2가 변수일 때, var1var2의 값을 생성합니다. 거듭제곱 연산자는 우결합성을 가집니다. 따라서 a ** b ** ca ** (b ** c)와 같습니다.

- -

구문

- -
연산자: var1 ** var2
-
- -

참고

- -

PHP와 Python 등 거듭제곱 연산자를 가진 대부분의 언어는 거듭제곱 연산자의 우선순위가 +와 - 등 단항 연산자보다 높습니다. 그러나 Bash는 단항 연산자가 거듭제곱 연산자보다 우선순위가 높은 등 일부 예외도 있습니다. JavaScript는 단항 연산자(+/-/~/!/delete/void/typeof)를 왼쪽 피연산자 앞에 배치할 수 없으므로, 모호한 표현도 작성할 수 없습니다.

- -
-2 ** 2;
-// Bash에서 4, 다른 언어에서는 -4.
-// 모호한 표현이므로 JavaScript에서는 유효하지 않음
-
-
--(2 ** 2);
-// JavaScript에서 -4, 작성자의 의도가 명확함
-
- -

예제

- -
2 ** 3 // 8
-3 ** 2 // 9
-3 ** 2.5 // 15.588457268119896
-10 ** -1 // 0.1
-NaN ** 2 // NaN
-
-2 ** 3 ** 2 // 512
-2 ** (3 ** 2) // 512
-(2 ** 3) ** 2 // 64
-
- -

결과의 부호를 뒤집으려면 다음과 같이 작성합니다.

- -
-(2 ** 2) // -4
-
- -

거듭제곱의 밑을 음수로 강제하려면 다음과 같이 작성합니다.

- -
(-2) ** 2 // 4
-
- -
-

참고: JavaScript는 비트 연산자 ^ (논리 XOR)도 가지고 있습니다. **^는 다릅니다. (예 : 2 ** 3 === 8이지만 2 ^ 3 === 1)

-
- -

증가 (++)

- -

증가 연산자는 피연산자를 증가(1을 덧셈)시키고, 그 값을 반환합니다.

- - - -

구문

- -
연산자: x++ or ++x
-
- -

예제

- -
// 접미사
-var x = 3;
-y = x++; // y = 3, x = 4
-
-// 접두사
-var a = 2;
-b = ++a; // a = 3, b = 3
-
- -

감소 (--)

- -

감소 연산자는 피연산자를 감소(1을 뺄셈)시키고, 그 값을 반환합니다.

- - - -

구문

- -
연산자: x-- or --x
-
- -

예제

- -
// 접미사
-var x = 3;
-y = x--; // y = 3, x = 2
-
-// 접두사
-var a = 2;
-b = --a; // a = 1, b = 1
-
- -

단항 부정 (-)

- -

단항 부정 연산자는 피연산자의 앞에 위치하며 부호를 뒤집습니다.

- -

구문

- -
연산자: -x
-
- -

예제

- -
var x = 3;
-y = -x; // y = -3, x = 3
-
-// 단항 부정 연산자는 숫자가 아닌 값을 숫자로 변환함
-var x = "4";
-y = -x; // y = -4
- -

단항 양부호 (+)

- -

단항 양부호 연산자는 피연산자의 앞에 위치하며 피연산자의 값 그대로 평가되지만, 값이 숫자가 아닐 경우 숫자로 변환을 시도합니다. 단항 부정(-) 연산자도 숫자가 아닌 값을 변환할 수 있지만, 단항 양부호가 속도도 제일 빠르고 다른 연산도 수행하지 않으므로 선호해야 할 방법입니다. 문자열로 표현한 정수 및 부동소수점 실수, 문자열이 아닌 true, false, null도 변환할 수 있습니다. 10진수와 (앞에 "0x"가 붙은) 16진수 정수 모두 지원합니다. 음수도 지원하지만 16진수 음수에는 사용할 수 없습니다. 어떤 값을 분석할 수 없으면 {{jsxref("NaN")}}으로 평가됩니다.

- -

구문

- -
연산자: +x
-
- -

예제

- -
+3     // 3
-+"3"   // 3
-+true  // 1
-+false // 0
-+null  // 0
-+function(val) { return val } // NaN
-
- -

명세

- - - - - - - - - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-additive-operators', 'Additive operators')}}
{{SpecName('ESDraft', '#sec-postfix-expressions', 'Postfix expressions')}}
{{SpecName('ESDraft', '#sec-11.5', 'Multiplicative operators')}}
{{SpecName('ESDraft', '#sec-11.4', 'Unary operator')}}
- -

브라우저 호환성

- - - -

{{Compat("javascript.operators.arithmetic")}}

- -

같이 보기

- - diff --git a/files/ko/web/javascript/reference/operators/assignment_operators/index.html b/files/ko/web/javascript/reference/operators/assignment_operators/index.html deleted file mode 100644 index 93146d63cf..0000000000 --- a/files/ko/web/javascript/reference/operators/assignment_operators/index.html +++ /dev/null @@ -1,395 +0,0 @@ ---- -title: 할당 연산자 -slug: Web/JavaScript/Reference/Operators/Assignment_Operators -tags: - - JavaScript - - Operator - - Reference -translation_of: Web/JavaScript/Reference/Operators#Assignment_operators -translation_of_original: Web/JavaScript/Reference/Operators/Assignment_Operators ---- -
{{jsSidebar("Operators")}}
- -

할당 연산자는 오른쪽 피연산자의 값을 왼쪽 피연산자에 할당합니다.

- -
{{EmbedInteractiveExample("pages/js/expressions-assignment.html")}}
- - - -

개요

- -

기본 할당연산자는 등호(=)로, 오른쪽 피연산자의 값을 왼쪽 피연산자에 할당합니다. 즉, x = yy의 값을 x에 할당힙니다. 다른 할당 연산자는 보통 표준 연산의 축약형으로, 다음 표에서 종류와 예시를 확인할 수 있습니다.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
이름단축 연산자의미
할당x = yx = y
덧셈 할당x += yx = x + y
뺄셈 할당x -= yx = x - y
곱셈 할당x *= yx = x * y
나눗셈 할당x /= yx = x / y
나머지 연산 할당x %= yx = x % y
지수 연산 할당x **= yx = x ** y
왼쪽 시프트 할당x <<= yx = x << y
오른쪽 시프트 할당x >>= yx = x >> y
부호없는 오른쪽 시프트 할당x >>>= yx = x >>> y
비트 AND 할당x &= yx = x & y
비트 XOR 할당x ^= yx = x ^ y
비트 OR 할당x |= yx = x | y
- -

할당

- -

단순 할당 연산자는 값을 변수에 할당합니다. 할당 연산자는 할당의 결과값으로 평가됩니다. 할당 연산자를 연속해서 사용해, 다수의 변수에 하나의 값을 한꺼번에 할당할 수 있습니다. 예제를 참고하세요.

- -

구문

- -
연산자: x = y
-
- -

예제

- -
// 다음과 같은 변수를 가정
-//  x = 5
-//  y = 10
-//  z = 25
-
-x = y     // x는 10
-x = y = z // x, y, z 모두 25
-
- -

덧셈 할당

- -

덧셈 할당 연산자는 변수에 오른쪽 피연산자의 값을 더하고, 그 결과를 변수에 할당합니다. 두 피연산자의 자료형이 덧셈 할당 연산자의 행동을 결정합니다. 덧셈 연산자처럼 합 또는 연결이 가능합니다. 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "덧셈 연산자", "#Addition", 1)}}를 참고하세요.

- -

구문

- -
연산자: x += y
-의미: x = x + y
-
- -

예제

- -
// 다음과 같은 변수를 가정
-//  foo = "foo"
-//  bar = 5
-//  baz = true
-
-
-// Number + Number -> 합
-bar += 2 // 7
-
-// Boolean + Number -> 합
-baz += 1 // 2
-
-// Boolean + Boolean -> 합
-baz += false // 1
-
-// Number + String -> 연결
-bar += 'foo' // "5foo"
-
-// String + Boolean -> 연결
-foo += false // "foofalse"
-
-// String + String -> 연결
-foo += 'bar' // "foobar"
-
- -

뺄셈 할당

- -

뺄셈 할당 연산자는 변수에서 오른쪽 피연산자의 값을 빼고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "뺄셈 연산자", "#Subtraction", 1)}}를 참고하세요.

- -

구문

- -
연산자: x -= y
-의미: x = x - y
-
- -

예제

- -
// 다음과 같은 변수를 가정
-//  bar = 5
-
-bar -= 2     // 3
-bar -= "foo" // NaN
-
- -

곱셈 할당

- -

곱셈 할당 연산자는 변수에 오른쪽 피연산자의 값을 곱하고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "곱셈 연산자", "#Multiplication", 1)}}를 참고하세요.

- -

구문

- -
연산자: x *= y
-의미: x = x * y
-
- -

예제

- -
// 다음과 같은 변수를 가정
-//  bar = 5
-
-bar *= 2     // 10
-bar *= "foo" // NaN
-
- -

나눗셈 할당

- -

나눗셈 할당 연산자는 변수를 오른쪽 피연산자로 나누고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "나눗셈 연산자", "#Division", 1)}}를 참고하세요.

- -

구문

- -
연산자: x /= y
-의미: x = x / y
-
- -

예제

- -
// 다음과 같은 변수를 가정
-//  bar = 5
-
-bar /= 2     // 2.5
-bar /= "foo" // NaN
-bar /= 0     // Infinity
-
- -

나머지 연산 할당

- -

나머지 연산 할당은 변수를 오른쪽 피연산자로 나눈 나머지를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "나머지 연산자", "#Remainder", 1)}}를 참고하세요.

- -

구문

- -
연산자: x %= y
-의미: x = x % y
-
- -

예제

- -
// 다음과 같은 변수를 가정
-//  bar = 5
-
-bar %= 2     // 1
-bar %= "foo" // NaN
-bar %= 0     // NaN
-
- -

거듭제곱 할당

- -

거듭제곱 할당 연산자는 변수를 오른쪽 피연산자만큼 거듭제곱한 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "거듭제곱 연산자", "#Exponentiation", 1)}}를 참고하세요.

- -

구문

- -
연산자: x **= y
-의미: x = x ** y
-
- -

예제

- -
// 다음과 같은 변수를 가정
-//  bar = 5
-
-bar **= 2     // 25
-bar **= "foo" // NaN
- -

왼쪽 시프트 할당

- -

왼쪽 시프트 할당 연산자는 변수의 비트를 오른쪽 피연산자의 값만큼 왼쪽으로 이동하고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "left shift operator", "#Left_shift", 1)}}를 참고하세요.

- -

구문

- -
연산자: x <<= y
-의미: x = x << y
-
- -

예제

- -
var bar = 5; //  (00000000000000000000000000000101)
-bar <<= 2; // 20 (00000000000000000000000000010100)
-
- -

오른쪽 시프트 할당

- -

오른쪽 시프트 할당 연산자는 변수의 비트를 오른쪽 피연산자의 값만큼 우측으로 이동하고, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "right shift operator", "#Right_shift", 1)}}를 참고하세요.

- -

구문

- -
연산자: x >>= y
-의미: x = x >> y
-
- -

예제

- -
var bar = 5; //   (00000000000000000000000000000101)
-bar >>= 2;   // 1 (00000000000000000000000000000001)
-
-var bar -5; //    (-00000000000000000000000000000101)
-bar >>= 2;  // -2 (-00000000000000000000000000000010)
-
- -

부호 없는 오른쪽 시프트 할당

- -

부호 없는 오른쪽 시프트 할당 연산자는 변수의 비트를 오른쪽 피연산자의 값만큼 우측으로 이동하고, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", " unsigned right shift operator", "#Unsigned_right_shift", 1)}}을 참고하세요.

- -

구문

- -
연산자: x >>>= y
-의미: x = x >>> y
-
- -

예제

- -
var bar = 5; //   (00000000000000000000000000000101)
-bar >>>= 2;  // 1 (00000000000000000000000000000001)
-
-var bar = -5; // (-00000000000000000000000000000101)
-bar >>>= 2; // 1073741822 (00111111111111111111111111111110)
- -

비트 AND 할당

- -

비트 AND 할당 연산자는 양쪽 피연산자의 이진 표현을 AND 연산한 후, 그 결과를 변수에 할당합니다. 자세한 내용은{{jsxref("Operators/Bitwise_Operators", "bitwise AND operator", "#Bitwise_AND", 1)}}을 참고하세요.

- -

구문

- -
연산자: x &= y
-의미: x = x & y
-
- -

예제

- -
var bar = 5;
-// 5:     00000000000000000000000000000101
-// 2:     00000000000000000000000000000010
-bar &= 2; // 0
-
- -

비트 XOR 할당

- -

비트 XOR 할당 연산자는 양쪽 피연산자의 이진 표현을 XOR 연산한 후, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "bitwise XOR operator", "#Bitwise_XOR", 1)}}를 참고하세요.

- -

구문

- -
연산자: x ^= y
-의미: x = x ^ y
-
- -

예제

- -
var bar = 5;
-bar ^= 2; // 7
-// 5: 00000000000000000000000000000101
-// 2: 00000000000000000000000000000010
-// -----------------------------------
-// 7: 00000000000000000000000000000111
-
- -

비트 OR 할당

- -

비트 OR 할당 연산자는 양쪽 피연산자의 이진 표현을 OR 연산한 후, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "bitwise OR operator", "#Bitwise_OR", 1)}}를 참고하세요.

- -

문법

- -
연산자: x |= y
-의미: x = x | y
-
- -

예제

- -
var bar = 5;
-bar |= 2; // 7
-// 5: 00000000000000000000000000000101
-// 2: 00000000000000000000000000000010
-// -----------------------------------
-// 7: 00000000000000000000000000000111
-
- -

예제

- -

다른 할당 연산자를 갖는 왼쪽 피연산자

- -

드물게, 할당 연산자(예: x += y)와 그 의미를 나타낸 표현(x = x + y)이 동일하지 않은 경우가 있습니다. 할당 연산자의 왼쪽 피연산자가 다른 할당 연산자를 포함할 때, 왼쪽 피연산자는 한 번만 평가됩니다. 예를 들면 다음과 같습니다.

- -
a[i++] += 5         // i는 한 번만 평가됨
-a[i++] = a[i++] + 5 // i는 두 번 평가됨
-
- -

명세

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}
- -

브라우저 호환성

- - - -

{{Compat("javascript.operators.assignment")}}

- -

같이 보기

- - diff --git a/files/ko/web/javascript/reference/operators/bitwise_operators/index.html b/files/ko/web/javascript/reference/operators/bitwise_operators/index.html deleted file mode 100644 index 4cc5ab7b5a..0000000000 --- a/files/ko/web/javascript/reference/operators/bitwise_operators/index.html +++ /dev/null @@ -1,541 +0,0 @@ ---- -title: 비트 연산자 -slug: Web/JavaScript/Reference/Operators/Bitwise_Operators -tags: - - JavaScript - - Operator - - Reference -translation_of: Web/JavaScript/Reference/Operators -translation_of_original: Web/JavaScript/Reference/Operators/Bitwise_Operators ---- -
{{jsSidebar("Operators")}}
- -

비트 연산자는 피연산자를 10진수, 16진수, 8진수가 아니라, 32개의 비트(0과 1) 집합으로 취급합니다. 예를 들어, 10진수 9의 2진수 표기법은 1001입니다. 이렇게, 비트 연산자는 값의 2진수 표현을 사용해 연산하지만, 결과는 표준 JavaScript 숫자 값으로 반환합니다.

- -
{{EmbedInteractiveExample("pages/js/expressions-bitwiseoperators.html")}}
- - - -

다음은 JavaScript의 비트 연산자를 요약한 표입니다.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
연산자사용방법설명
비트 ANDa & b피연산자를 비트로 바꿨을 때 각각 대응하는 비트가 모두 1이면 그 비트값에 1을 반환.
비트 ORa | b피연산자를 비트로 바꿨을 때 각각 대응하는 비트가 모두 1이거나 한 쪽이 1이면 1을 반환.
비트 XORa ^ b피연산자를 비트로 바꿨을 때 대응하는 비트가 서로 다르면 1을 반환.
비트 NOT~ a피연산자의 반전된 값을 반환.
왼쪽 시프트a << bShifts a in binary representation b (< 32) bits to the left, shifting in zeros from the right.
부호 유지 오른쪽 시프트a >> bShifts a in binary representation b (< 32) bits to the right, discarding bits shifted off.
부호 버림 오른쪽 시프트a >>> bShifts a in binary representation b (< 32) bits to the right, discarding bits shifted off, and shifting in zeros from the left.
- -

부호 있는 32비트 정수

- -

The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format, except for zero-fill right shift which results in an unsigned 32-bit integer.

- -

Two's complement format means that a number's negative counterpart (e.g. 5 vs. -5) is all the number's bits inverted (bitwise NOT of the number, or ones' complement of the number) plus one.

- -

For example, the following encodes the integer 314:

- -
00000000000000000000000100111010
-
- -

The following encodes ~314, i.e. the one's complement of 314:

- -
11111111111111111111111011000101
-
- -

Finally, the following encodes -314, i.e. the two's complement of 314:

- -
11111111111111111111111011000110
-
- -

The two's complement guarantees that the left-most bit is 0 when the number is positive and 1 when the number is negative. Thus, it is called the sign bit.

- -

The number 0 is the integer that is composed completely of 0 bits.

- -
0 (base 10) = 00000000000000000000000000000000 (base 2)
-
- -

The number -1 is the integer that is composed completely of 1 bits.

- -
-1 (base 10) = 11111111111111111111111111111111 (base 2)
-
- -

The number -2147483648 (hexadecimal representation: -0x80000000) is the integer that is composed completely of 0 bits except the first (left-most) one.

- -
-2147483648 (base 10) = 10000000000000000000000000000000 (base 2)
-
- -

The number 2147483647 (hexadecimal representation: 0x7fffffff) is the integer that is composed completely of 1 bits except the first (left-most) one.

- -
2147483647 (base 10) = 01111111111111111111111111111111 (base 2)
-
- -

The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable throught a 32bit signed number.

- -

비트 논리 연산자

- -

비트 논리 연산자는 다음과 같이 사용됩니다.

- - - -

& (비트 AND)

- -

비트 연산자 AND를 비트 쌍으로 실행합니다.

- -

Performs the AND operation on each pair of bits. a AND b yields 1 only if both a and b are 1. The truth table for the AND operation is:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
aba AND b
000
010
100
111
- -
     9 (base 10) = 00000000000000000000000000001001 (base 2)
-    14 (base 10) = 00000000000000000000000000001110 (base 2)
-                   --------------------------------
-14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10)
-
- -

Bitwise ANDing any number x with 0 yields 0. Bitwise ANDing any number x with -1 yields x.

- -

| (비트 OR)

- -

Performs the OR operation on each pair of bits. a OR b yields 1 if either a or b is 1. The truth table for the OR operation is:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
aba OR b
000
011
101
111
- -
     9 (base 10) = 00000000000000000000000000001001 (base 2)
-    14 (base 10) = 00000000000000000000000000001110 (base 2)
-                   --------------------------------
-14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)
-
- -

Bitwise ORing any number x with 0 yields x.

- -

Bitwise ORing any number x with -1 yields -1.

- -

^ (비트 XOR)

- -

Performs the XOR operation on each pair of bits. a XOR b yields 1 if a and b are different. The truth table for the XOR operation is:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
aba XOR b
000
011
101
110
- -
     9 (base 10) = 00000000000000000000000000001001 (base 2)
-    14 (base 10) = 00000000000000000000000000001110 (base 2)
-                   --------------------------------
-14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)
-
- -

Bitwise XORing any number x with 0 yields x.

- -

Bitwise XORing any number x with -1 yields ~x.

- -

~ (비트 NOT)

- -

Performs the NOT operator on each bit. NOT a yields the inverted value (a.k.a. one's complement) of a. The truth table for the NOT operation is:

- - - - - - - - - - - - - - - - -
aNOT a
01
10
- -
 9 (base 10) = 00000000000000000000000000001001 (base 2)
-               --------------------------------
-~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)
-
- -

Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.

- -

비트 시프트 연산자

- -

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

- -

Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the same type as the left operand. The right operand should be less than 32, but if not only the low five bits will be used.

- -

<< (Left shift)

- -

This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.

- -

For example, 9 << 2 yields 36:

- -
     9 (base 10): 00000000000000000000000000001001 (base 2)
-                  --------------------------------
-9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10)
-
- -

Bitwise shifting any number x to the left by y bits yields x * 2^y.

- -

>> (Sign-propagating right shift)

- -

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".

- -

For example, 9 >> 2 yields 2:

- -
     9 (base 10): 00000000000000000000000000001001 (base 2)
-                  --------------------------------
-9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
-
- -

Likewise, -9 >> 2 yields -3, because the sign is preserved:

- -
     -9 (base 10): 11111111111111111111111111110111 (base 2)
-                   --------------------------------
--9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
-
- -

>>> (Zero-fill right shift)

- -

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always non-negative.

- -

For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. For example, 9 >>> 2 yields 2, the same as 9 >> 2:

- -
      9 (base 10): 00000000000000000000000000001001 (base 2)
-                   --------------------------------
-9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
-
- -

However, this is not the case for negative numbers. For example, -9 >>> 2 yields 1073741821, which is different than -9 >> 2 (which yields -3):

- -
      -9 (base 10): 11111111111111111111111111110111 (base 2)
-                    --------------------------------
--9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
-
- -

예제

- -

Flags and bitmasks

- -

The bitwise logical operators are often used to create, manipulate, and read sequences of flags, which are like binary variables. Variables could be used instead of these sequences, but binary flags take much less memory (by a factor of 32).

- -

Suppose there are 4 flags:

- - - -

These flags are represented by a sequence of bits: DCBA. When a flag is set, it has a value of 1. When a flag is cleared, it has a value of 0. Suppose a variable flags has the binary value 0101:

- -
var flags = 5;   // binary 0101
-
- -

This value indicates:

- - - -

Since bitwise operators are 32-bit, 0101 is actually 00000000000000000000000000000101, but the preceding zeroes can be neglected since they contain no meaningful information.

- -

A bitmask is a sequence of bits that can manipulate and/or read flags. Typically, a "primitive" bitmask for each flag is defined:

- -
var FLAG_A = 1; // 0001
-var FLAG_B = 2; // 0010
-var FLAG_C = 4; // 0100
-var FLAG_D = 8; // 1000
-
- -

New bitmasks can be created by using the bitwise logical operators on these primitive bitmasks. For example, the bitmask 1011 can be created by ORing FLAG_A, FLAG_B, and FLAG_D:

- -
var mask = FLAG_A | FLAG_B | FLAG_D; // 0001 | 0010 | 1000 => 1011
-
- -

Individual flag values can be extracted by ANDing them with a bitmask, where each bit with the value of one will "extract" the corresponding flag. The bitmask masks out the non-relevant flags by ANDing with zeros (hence the term "bitmask"). For example, the bitmask 0100 can be used to see if flag C is set:

- -
// if we own a cat
-if (flags & FLAG_C) { // 0101 & 0100 => 0100 => true
-   // do stuff
-}
-
- -

A bitmask with multiple set flags acts like an "either/or". For example, the following two are equivalent:

- -
// if we own a bat or we own a cat
-if ((flags & FLAG_B) || (flags & FLAG_C)) { // (0101 & 0010) || (0101 & 0100) => 0000 || 0100 => true
-   // do stuff
-}
-
- -
// if we own a bat or cat
-var mask = FLAG_B | FLAG_C; // 0010 | 0100 => 0110
-if (flags & mask) { // 0101 & 0110 => 0100 => true
-   // do stuff
-}
-
- -

Flags can be set by ORing them with a bitmask, where each bit with the value one will set the corresponding flag, if that flag isn't already set. For example, the bitmask 1100 can be used to set flags C and D:

- -
// yes, we own a cat and a duck
-var mask = FLAG_C | FLAG_D; // 0100 | 1000 => 1100
-flags |= mask;   // 0101 | 1100 => 1101
-
- -

Flags can be cleared by ANDing them with a bitmask, where each bit with the value zero will clear the corresponding flag, if it isn't already cleared. This bitmask can be created by NOTing primitive bitmasks. For example, the bitmask 1010 can be used to clear flags A and C:

- -
// no, we don't have an ant problem or own a cat
-var mask = ~(FLAG_A | FLAG_C); // ~0101 => 1010
-flags &= mask;   // 1101 & 1010 => 1000
-
- -

The mask could also have been created with ~FLAG_A & ~FLAG_C (De Morgan's law):

- -
// no, we don't have an ant problem, and we don't own a cat
-var mask = ~FLAG_A & ~FLAG_C;
-flags &= mask;   // 1101 & 1010 => 1000
-
- -

Flags can be toggled by XORing them with a bitmask, where each bit with the value one will toggle the corresponding flag. For example, the bitmask 0110 can be used to toggle flags B and C:

- -
// if we didn't have a bat, we have one now, and if we did have one, bye-bye bat
-// same thing for cats
-var mask = FLAG_B | FLAG_C;
-flags = flags ^ mask;   // 1100 ^ 0110 => 1010
-
- -

Finally, the flags can all be flipped with the NOT operator:

- -
// entering parallel universe...
-flags = ~flags;    // ~1010 => 0101
-
- -

Conversion snippets

- -

Convert a binary string to a decimal number:

- -
var sBinString = "1011";
-var nMyNumber = parseInt(sBinString, 2);
-alert(nMyNumber); // prints 11, i.e. 1011
-
- -

Convert a decimal number to a binary string:

- -
var nMyNumber = 11;
-var sBinString = nMyNumber.toString(2);
-alert(sBinString); // prints 1011, i.e. 11
-
- -

Automate Mask Creation

- -

If you have to create many masks from some boolean values, you can automatize the process:

- -
function createMask () {
-  var nMask = 0, nFlag = 0, nLen = arguments.length > 32 ? 32 : arguments.length;
-  for (nFlag; nFlag < nLen; nMask |= arguments[nFlag] << nFlag++);
-  return nMask;
-}
-var mask1 = createMask(true, true, false, true); // 11, i.e.: 1011
-var mask2 = createMask(false, false, true); // 4, i.e.: 0100
-var mask3 = createMask(true); // 1, i.e.: 0001
-// etc.
-
-alert(mask1); // prints 11, i.e.: 1011
-
- -

Reverse algorithm: an array of booleans from a mask

- -

If you want to create an array of booleans from a mask you can use this code:

- -
function arrayFromMask (nMask) {
-  // nMask must be between -2147483648 and 2147483647
-  if (nMask > 0x7fffffff || nMask < -0x80000000) { throw new TypeError("arrayFromMask - out of range"); }
-  for (var nShifted = nMask, aFromMask = []; nShifted; aFromMask.push(Boolean(nShifted & 1)), nShifted >>>= 1);
-  return aFromMask;
-}
-
-var array1 = arrayFromMask(11);
-var array2 = arrayFromMask(4);
-var array3 = arrayFromMask(1);
-
-alert("[" + array1.join(", ") + "]");
-// prints "[true, true, false, true]", i.e.: 11, i.e.: 1011
-
- -

You can test both algorithms at the same time…

- -
var nTest = 19; // our custom mask
-var nResult = createMask.apply(this, arrayFromMask(nTest));
-
-alert(nResult); // 19
-
- -

For didactic purpose only (since there is the Number.toString(2) method), we show how it is possible to modify the arrayFromMask algorithm in order to create a string containing the binary representation of a number, rather than an array of booleans:

- -
function createBinaryString (nMask) {
-  // nMask must be between -2147483648 and 2147483647
-  for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32; nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
-  return sMask;
-}
-
-var string1 = createBinaryString(11);
-var string2 = createBinaryString(4);
-var string3 = createBinaryString(1);
-
-alert(string1);
-// prints 00000000000000000000000000001011, i.e. 11
-
- -

명세

- - - - - - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-bitwise-not-operator', 'Bitwise NOT Operator')}}
{{SpecName('ESDraft', '#sec-binary-bitwise-operators', 'Binary Bitwise Operators')}}
{{SpecName('ESDraft', '#sec-bitwise-shift-operators', 'Bitwise Shift Operators')}}
- -

브라우저 호환성

- -

{{Compat("javascript.operators.bitwise")}}

- -

같이 보기

- - diff --git a/files/ko/web/javascript/reference/operators/comparison_operators/index.html b/files/ko/web/javascript/reference/operators/comparison_operators/index.html deleted file mode 100644 index cf5ae3afa2..0000000000 --- a/files/ko/web/javascript/reference/operators/comparison_operators/index.html +++ /dev/null @@ -1,216 +0,0 @@ ---- -title: 비교 연산자 -slug: Web/JavaScript/Reference/Operators/Comparison_Operators -tags: - - JavaScript - - Operator - - Reference -translation_of: Web/JavaScript/Reference/Operators -translation_of_original: Web/JavaScript/Reference/Operators/Comparison_Operators ---- -
{{jsSidebar("Operators")}}
- -

JavaScript는 엄격한 비교와 형변환 비교 두 가지의 비교 방법을 모두 가지고 있습니다. 엄격(일치) 비교(===)는 두 피연산자가 같은 자료형에, 그 내용도 일치해야만 참입니다. 추상(동등) 비교(==)는 비교 전에 두 피연산자를 동일한 자료형으로 변환합니다. 관계 추상 비교(<=)의 경우 {{glossary("primitive", "원시값")}}으로 바꾸고, 같은 자료형으로 다시 바꾼후 비교를 수행합니다.

- -

문자열의 경우 {{glossary("unicode", "유니코드")}} 값을 사용한 사전순으로 비교합니다.

- -
{{EmbedInteractiveExample("pages/js/expressions-comparisonoperators.html")}}
- - - -

비교 연산의 특징은 다음과 같습니다.

- - - -

동치 연산자

- -

동등 연산자 (==)

- -

동등 연산자는 두 피연산자의 자료형이 같지 않은 경우 같아지도록 변환한 후, 엄격 비교를 수행합니다. 피연산자가 모두 객체라면, JavaScript는 내부 참조를 보고, 둘 다 메모리의 같은 객체를 바라보고 있는지 판별합니다.

- -

구문

- -
x == y
-
- -

예제

- -
  1   ==  1        // true
- "1"  ==  1        // true
-  1   == '1'       // true
-  0   == false     // true
-  0   == null      // false
-
-  0   == undefined // false
-null  == undefined // true
-
- -

부등 연산자 (!=)

- -

부등 연산자는 두 피연산자가 같지 않은 경우 참을 반환합니다. 피연산자의 자료형이 일치하지 않는 경우 적절한 자료형으로의 변환을 시도합니다. 피연산자가 모두 객체라면, JavaScript는 내부 참조를 보고, 서로 메모리의 다른 객체를 바라보고 있는지 판별합니다.

- -

구문

- -
x != y
- -

예제

- -
1 !=   2     // true
-1 !=  "1"    // false
-1 !=  '1'    // false
-1 !=  true   // false
-0 !=  false  // false
-
- -

일치 연산자 (===)

- -

일치 연산자는 자료형 변환 없이 두 연산자가 엄격히 같은지 판별합니다.

- -

구문

- -
x === y
- -

예제

- -
3 === 3   // true
-3 === '3' // false
- -

불일치 연산자 (!==)

- -

일치 연산자는 두 연산자가 같지 않거나, 같은 자료형이 아닐 때 참을 반환합니다.

- -

구문

- -
x !== y
- -

예제

- -
3 !== '3' // true
-4 !== 3   // true
-
- -

관계 연산자

- -

이 항목의 모든 연산자는 비교 전에 피연산자를 {{glossary("primitive", "원시값")}}으로 변환합니다. 둘 다 문자열이 되는 경우 사전순으로 비교하고, 그렇지 않으면 숫자로 변환합니다. {{jsxref("NaN")}}과의 비교는 항상 false를 반환합니다.

- -

초과 연산자 (>)

- -

초과 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 큰 경우 참을 반환합니다.

- -

구문

- -
x > y
- -

예제

- -
4 > 3 // true
-
- -

이상 연산자 (>=)

- -

이상 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 크거나 같으면 참을 반환합니다.

- -

구문

- -
 x >= y
- -

예제

- -
4 >= 3 // true
-3 >= 3 // true
-
- -

미만 연산자 (<)

- -

미만 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 작은 경우 참을 반환합니다.

- -

구문

- -
x < y
- -

예제

- -
3 < 4 // true
- -

이하 연산자 (<=)

- -

이하 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 작거나 같으면 참을 반환합니다.

- -

구문

- -
 x <= y
- -

예제

- -
3 <= 4 // true
-
- -

동치 연산자 사용하기

- -

표준 동치, 동등 연산자(==, !=)는 두 피연산자를 비교하기 위해 추상 동치 비교 알고리즘(Abstract Equlity Comparison Algorithm)을 사용합니다. 피연산자 간 자료형이 일치하지 않으면 우선 변환을 시도합니다. 예를 들어 표현식 5 == '5'에서는 비교 전 오른쪽 문자열을 {{jsxref("Number")}}로 변환합니다.

- -

엄격 동치, 일치 연산자(===, !==)는 엄격 동치 비교 알고리즘(Strict Equality Comparison Algorithm)을 사용하며, 같은 자료형을 가진 피연산자를 비교하기 위해 사용합니다. 피연산자 간 자료형이 일치하지 않으면 항상 false이므로, 5 !== '5'입니다.

- -

피연산자의 값은 물론 특정 자료형이어야 하는 경우 일치 연산자를 사용하세요. 그렇지 않은 경우 형변환을 자동으로 해주는 동등 연산자를 사용할 수도 있습니다.

- -

비교 과정에 자료형 변환이 필요한 경우 JavaScript는 {{jsxref("String")}}, {{jsxref("Number")}}, {{jsxref("Boolean")}}, {{jsxref("Object")}} 자료형을 다음과 같이 변환합니다.

- - - -
참고: String 객체는 자료형 객체지, 문자열이 아닙니다! String 객체는 거의 쓰이지 않으며, 이런 성질로 인해 아래의 결과는 예상치 못한 값일 수 있습니다.
- -
// true as both operands are type String (i.e. string primitives):
-'foo' === 'foo'
-
-var a = new String('foo');
-var b = new String('foo');
-
-// false as a and b are type Object and reference different objects
-a == b
-
-// false as a and b are type Object and reference different objects
-a === b
-
-// true as a and 'foo' are of different type and, the Object (a)
-// is converted to String 'foo' before comparison
-a == 'foo'
- -

명세

- - - - - - - - - - - - - -
Status
{{SpecName('ESDraft', '#sec-equality-operators', 'Equality Operators')}}
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}
- -

브라우저 호환성

- -

{{Compat("javascript.operators.comparison")}}

- -

같이 보기

- - diff --git a/files/ko/web/javascript/reference/operators/operator_precedence/index.html b/files/ko/web/javascript/reference/operators/operator_precedence/index.html new file mode 100644 index 0000000000..7a82346d09 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/operator_precedence/index.html @@ -0,0 +1,462 @@ +--- +title: 연산자 우선순위 +slug: Web/JavaScript/Reference/Operators/연산자_우선순위 +tags: + - JavaScript + - Operator + - 연산자 + - 우선순위 +translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence +--- +
{{jsSidebar("Operators")}}
+ +

연산자 우선순위는 연산자를 실행하는 순서를 결정합니다. 우선순위가 높은 연산자가 먼저 실행됩니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}
+ + + +

우선순위와 결합성

+ +

아래와 같이 표현할 수 있는 표현식을 생각해 봅시다. 연산자1과 연산자2의 자리에는 아무 연산자를 넣을 수 있습니다.

+ +
a 연산자1 b 연산자2 c
+ +

두 연산자의 우선순위(아래 표 참조)가 다를 경우, 우선순위가 높은 연산자가 먼저 실행되고 결합성은 영향을 미치지 않습니다. 아래 예제에서는 덧셈이 곱셈보다 먼저 쓰였음에도 곱셈의 우선순위가 높기 때문에 먼저 실행됩니다.

+ +
console.log(3 + 10 * 2);   // 23을 출력
+console.log(3 + (10 * 2)); // 23을 출력, 괄호는 불필요함
+console.log((3 + 10) * 2); // 26을 출력, 괄호로 인해 실행 순서가 바뀜
+
+ +

좌결합성(왼쪽에서 오른쪽으로)은 표현식이 (a 연산자1 b) 연산자2 c와 같이, 우결합성(오른쪽에서 왼쪽으로)은 a 연산자1 (b 연산자2 c)와 같이 계산된다는 의미입니다. 대입 연산자는 우결합성이므로 다음과 같은 코드를 작성할 수 있습니다.

+ +
a = b = 5; // a = (b = 5);와 같음
+
+ +

이때 대입 연산자는 대입된 값을 반환하므로 ab의 값이 5가 됨을 예상할 수 있습니다. 우선 b의 값이 5로 설정되고, 그 다음에는 a의 값이 우변인 b = 5의 반환값 5로 설정됩니다.

+ +

다른 예시로, 좌결합성인 다른 산술 연산자와 달리 거듭제곱 연산자 (**)만은 우결합성입니다. 흥미로운 점으로 표현식의 평가는 결합성과 무관하게 항상 왼쪽에서 오른쪽으로 진행됩니다.

+ + + + + + + + + + + + + + + + +
코드출력
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 나눗셈 연산자 (/)에 주목
+console.log(echo("첫째", 6) / echo("둘째", 2));
+
+
+
+첫째 항 평가함
+둘째 항 평가함
+3
+
+
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 거듭제곱 연산자 (**)에 주목
+console.log(echo("첫째", 2) ** echo("둘째", 3));
+
+
+첫째 항 평가함
+둘째 항 평가함
+8
+
+ +

여러 연산자의 우선순위가 같을 때는 결합성을 고려합니다. 위에서와 같이 연산자가 하나이거나 연산자끼리 우선순위가 다를 경우에는 결합성이 결과에 영향을 미치지 않습니다. 아래의 예제에서 같은 종류의 연산자를 여러 번 사용했을 때 결합성이 결과에 영향을 미치는 것을 확인할 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + +
코드출력
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 나눗셈 연산자 (/)에 주목
+console.log(echo("첫째", 6) / echo("둘째", 2) / echo("셋째", 3));
+
+
+
+첫째 항 평가함
+둘째 항 평가함
+셋째 항 평가함
+1
+
+
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 거듭제곱 연산자 (**)에 주목
+console.log(echo("첫째", 2) ** echo("둘째", 3) ** echo("셋째", 2));
+
+
+
+첫째 항 평가함
+둘째 항 평가함
+셋째 항 평가함
+512
+
+
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 첫 번째 거듭제곱 연산자 주변의 괄호에 주목
+console.log((echo("첫째", 2) ** echo("둘째", 3)) ** echo("셋째", 2));
+
+
+첫째 항 평가함
+둘째 항 평가함
+셋째 항 평가함
+64
+
+ +

위의 예제에서 나눗셈은 좌결합성이므로 6 / 3 / 2(6 / 3) / 2와 같습니다. 한편 거듭제곱은 우결합성이므로 2 ** 3 ** 22 ** (3 ** 2)와 같습니다. 그러므로 (2 ** 3) ** 2는 괄호로 인해 실행 순서가 바뀌기 때문에 위 표와 같이 64로 평가됩니다.

+ +

우선순위는 결합성보다 항상 우선하므로, 거듭제곱과 나눗셈을 같이 사용하면 나눗셈보다 거듭제곱이 먼저 계산됩니다. 예를 들어 2 ** 3 / 3 ** 2는 (2 ** 3) / (3 ** 2)와 같으므로 0.8888888888888888로 계산됩니다.

+ +

예제

+ +
3 > 2 && 2 > 1
+// true를 반환
+
+3 > 2 > 1
+// 3 > 2는 true인데, 부등호 연산자에서 true는 1로 변환되므로
+// true > 1은 1 > 1이 되고, 이는 거짓이다.
+// 괄호를 추가하면 (3 > 2) > 1과 같다.
+ +

+ +

다음 표는 우선순위 내림차순(21부터 1까지)으로 정렬되어 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
우선순위연산자 유형결합성연산자
21{{jsxref("Operators/Grouping", "그룹", "", 1)}}없음( … )
20{{jsxref("Operators/Property_Accessors", "멤버 접근", "#점_표기법", 1)}}좌결합성… . …
{{jsxref("Operators/Property_Accessors", "계산된 멤버 접근","#괄호_표기법", "1")}}좌결합성… [ … ]
{{jsxref("Operators/new","new")}} (매개변수 리스트 존재)없음new … ( … )
+

함수 호출

+
좌결합성… ( )
Optional chaining좌결합성?.
19{{jsxref("Operators/new","new")}} (매개변수 리스트 생략)우결합성new …
18{{jsxref("Operators/Arithmetic_Operators","후위 증가","#Increment", 1)}}없음… ++
{{jsxref("Operators/Arithmetic_Operators","후위 감소","#Decrement", 1)}}… --
17논리 NOT우결합성! …
비트 NOT~ …
단항 양부호+ …
단항 부정- …
전위 증가++ …
전위 감소-- …
{{jsxref("Operators/typeof", "typeof")}}typeof …
{{jsxref("Operators/void", "void")}}void …
{{jsxref("Operators/delete", "delete")}}delete …
{{jsxref("Operators/await", "await")}}await …
16거듭제곱우결합성… ** …
15곱셈좌결합성… * …
나눗셈… / …
나머지… % …
14덧셈좌결합성… + …
뺄셈… - …
13비트 왼쪽 시프트좌결합성… << …
비트 오른쪽 시프트… >> …
비트 부호 없는 오른쪽 시프트… >>> …
12미만좌결합성… < …
이하… <= …
초과… > …
이상… >= …
{{jsxref("Operators/in", "in")}}… in …
{{jsxref("Operators/instanceof", "instanceof")}}… instanceof …
11동등좌결합성… == …
부등… != …
일치… === …
불일치… !== …
10비트 AND좌결합성… & …
9비트 XOR좌결합성… ^ …
8비트 OR좌결합성… | …
7널 병합 연산자좌결합성… ?? …
6논리 AND좌결합성… && …
5논리 OR좌결합성… || …
4조건우결합성… ? … : …
3할당우결합성… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2{{jsxref("Operators/yield", "yield")}}우결합성yield …
{{jsxref("Operators/yield*", "yield*")}}yield* …
1쉼표 / 시퀀스좌결합성… , …
diff --git "a/files/ko/web/javascript/reference/operators/\353\205\274\353\246\254_\354\227\260\354\202\260\354\236\220(logical_operators)/index.html" "b/files/ko/web/javascript/reference/operators/\353\205\274\353\246\254_\354\227\260\354\202\260\354\236\220(logical_operators)/index.html" deleted file mode 100644 index b442b1d7bd..0000000000 --- "a/files/ko/web/javascript/reference/operators/\353\205\274\353\246\254_\354\227\260\354\202\260\354\236\220(logical_operators)/index.html" +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: 논리 연산자 -slug: Web/JavaScript/Reference/Operators/논리_연산자(Logical_Operators) -tags: - - JavaScript - - Logic - - Not - - Operator - - Reference - - and - - or - - 논리 -translation_of: Web/JavaScript/Reference/Operators -translation_of_original: Web/JavaScript/Reference/Operators/Logical_Operators ---- -
{{jsSidebar("Operators")}}
- -

논리 연산자는 보통 {{jsxref("Boolean")}}(논리적) 값과 함께 쓰이며, 불리언 값을 반환합니다. 그런데, &&|| 연산자는 사실 피연산자 중 하나의 값을 반환합니다. 그러므로 불리언 외의 다른 값과 함께 사용하면 불리언 값이 아닌 것을 반환할 수 있습니다.

- -
{{EmbedInteractiveExample("pages/js/expressions-logicaloperator.html")}}
- - - -

설명

- -

다음 표는 논리 연산자의 종류입니다. (expr은 불리언을 포함해서 아무 자료형이나 가능합니다)

- - - - - - - - - - - - - - - - - - - - - - - - -
연산자구문설명
논리 AND (&&)expr1 && expr2expr1true로 변환할 수 있는 경우 expr2을 반환하고, 그렇지 않으면 expr1을 반환합니다.
논리 OR (||)expr1 || expr2 -

expr1true로 변환할 수 있으면 expr1을 반환하고, 그렇지 않으면 expr2를 반환합니다.

-
논리 NOT (!)!expr단일 피연산자를 true로 변환할 수 있으면 false를 반환합니다. 그렇지 않으면 true를 반환합니다.
- -

값을 true로 변환하면 값이 {{Glossary("truthy", "참")}}인 것입니다.
- 값을 false로 변환할 수 있으면 값이 {{Glossary("falsy", "거짓")}}인 것입니다.

- -

거짓으로 변환할 수 있는 표현의 예는 다음과 같습니다.

- - - -

&& 연산자와 || 연산자를 불리언 값이 아닌 피연산자와 함께 사용될 수 있지만, 반환 값을 항상 불리언 원시값으로 변환할 수 있으므로 불리언 연산자로 생각할 수 있습니다. 반환 값을 직접 불리언으로 바꾸려면 {{jsxref("Boolean")}} 함수나 이중 부정 연산자를 사용하세요.

- -

단락 평가

- -

논리 표현식을 좌측부터 평가하므로, 아래 규칙에 따라 단락(short-circuit) 평가를 수행합니다.

- - - -

"단락"이란, 위 규칙에서 expr을 평가하지 않는다는 뜻입니다. 따라서 평가 중 발생해야 할 부작용(예: expr이 함수 호출이면 절대 호출하지 않음)도 나타나지 않습니다. 단락 평가가 발생하는 원인은 첫 번째 피연산자를 평가한 순간 이미 연산자의 결과가 정해지기 때문입니다. 다음 예제를 살펴보세요.

- -
function A(){ console.log('A 호출'); return false; }
-function B(){ console.log('B 호출'); return true; }
-
-console.log( A() && B() );
-// 함수 호출로 인해 콘솔에 "A 호출" 기록
-// 그 후 연산자의 결과값인 "false" 기록
-
-console.log( B() || A() );
-// 함수 호출로 인해 콘솔에 "B 호출" 기록
-// 그 후 연산자의 결과인 "true" 기록
-
- -

연산자 우선순위

- -

다음 두 식은 똑같아 보이지만, && 연산자는 || 이전에 실행되므로 서로 다릅니다. 연산자 우선순위를 참고하세요.

- -
true || false && false      // returns true, because && is executed first
-(true || false) && false    // returns false, because operator precedence cannot apply
- -

논리 AND (&&)

- -

다음은 &&(논리 AND) 연산자의 예제입니다.

- -
a1 = true  && true       // t && t returns true
-a2 = true  && false      // t && f returns false
-a3 = false && true       // f && t returns false
-a4 = false && (3 == 4)   // f && f returns false
-a5 = 'Cat' && 'Dog'      // t && t returns "Dog"
-a6 = false && 'Cat'      // f && t returns false
-a7 = 'Cat' && false      // t && f returns false
-a8 = ''    && false      // f && f returns ""
-a9 = false && ''         // f && f returns false
- -

논리 OR (||)

- -

다음은 ||(논리 OR) 연산자의 예제입니다.

- -
o1 = true  || true       // t || t returns true
-o2 = false || true       // f || t returns true
-o3 = true  || false      // t || f returns true
-o4 = false || (3 == 4)   // f || f returns false
-o5 = 'Cat' || 'Dog'      // t || t returns "Cat"
-o6 = false || 'Cat'      // f || t returns "Cat"
-o7 = 'Cat' || false      // t || f returns "Cat"
-o8 = ''    || false      // f || f returns false
-o9 = false || ''         // f || f returns ""
-o10 = false || varObject // f || object returns varObject
-
- -

논리 NOT (!)

- -

다음은 !(논리 NOT) 연산자의 예제입니다.

- -
n1 = !true               // !t returns false
-n2 = !false              // !f returns true
-n3 = !''                 // !f returns true
-n4 = !'Cat'              // !t returns false
-
- -

이중 NOT (!!)

- -

NOT 연산자 다수를 연속해서 사용하면 아무 값이나 불리언 원시값으로 강제 변환할 수 있습니다. 변환 결과는 피연산자 값의 "참스러움"이나 "거짓스러움"에 따릅니다. ({{Glossary("truthy", "참")}}과 {{Glossary("falsy", "거짓")}}을 참고하세요)

- -

동일한 변환을 {{jsxref("Boolean")}} 함수로도 수행할 수 있습니다.

- -
n1 = !!true                   // !!truthy returns true
-n2 = !!{}                     // !!truthy returns true: any object is truthy...
-n3 = !!(new Boolean(false))   // ...even Boolean objects with a false .valueOf()!
-n4 = !!false                  // !!falsy returns false
-n5 = !!""                     // !!falsy returns false
-n6 = !!Boolean(false)         // !!falsy returns false
-
- -

불리언 변환 규칙

- -

AND에서 OR로 변환

- -

불리언 계산에서, 다음 두 코드는 항상 같습니다.

- -
bCondition1 && bCondition2
-
- -
!(!bCondition1 || !bCondition2)
- -

OR에서 AND로 변환

- -

불리언 계산에서, 다음 두 코드는 항상 같습니다.

- -
bCondition1 || bCondition2
-
- -
!(!bCondition1 && !bCondition2)
- -

NOT 간 변환

- -

불리언 계산에서, 다음 두 코드는 항상 같습니다.

- -
!!bCondition
-
- -
bCondition
- -

중첩 괄호 제거

- -

논리 표현식은 항상 왼쪽에서 오른쪽으로 평가되므로, 몇 가지 규칙을 따르면 복잡한 표현식에서 괄호를 제거할 수 있습니다.

- -

중첩 AND 제거

- -

불리언의 합성 계산에서, 다음 두 코드는 항상 같습니다.

- -
bCondition1 || (bCondition2 && bCondition3)
-
- -
bCondition1 || bCondition2 && bCondition3
- -

중첩 OR 제거

- -

불리언의 합성 계산에서, 다음 두 코드는 항상 같습니다.

- -
bCondition1 && (bCondition2 || bCondition3)
-
- -
!(!bCondition1 || !bCondition2 && !bCondition3)
- -

명세

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-11.11')}}{{Spec2('ES5.1')}}Defined in several sections of the specification: Logical NOT Operator, Binary Logical Operators
{{SpecName('ES6', '#sec-binary-logical-operators')}}{{Spec2('ES6')}}Defined in several sections of the specification: Logical NOT Operator, Binary Logical Operators
{{SpecName('ESDraft', '#sec-binary-logical-operators')}}{{Spec2('ESDraft')}}Defined in several sections of the specification: Logical NOT Operator, Binary Logical Operators
- -

브라우저 호환성

- - - -

{{Compat("javascript.operators.logical")}}

- -

같이 보기

- - diff --git "a/files/ko/web/javascript/reference/operators/\354\227\260\354\202\260\354\236\220_\354\232\260\354\204\240\354\210\234\354\234\204/index.html" "b/files/ko/web/javascript/reference/operators/\354\227\260\354\202\260\354\236\220_\354\232\260\354\204\240\354\210\234\354\234\204/index.html" deleted file mode 100644 index 7a82346d09..0000000000 --- "a/files/ko/web/javascript/reference/operators/\354\227\260\354\202\260\354\236\220_\354\232\260\354\204\240\354\210\234\354\234\204/index.html" +++ /dev/null @@ -1,462 +0,0 @@ ---- -title: 연산자 우선순위 -slug: Web/JavaScript/Reference/Operators/연산자_우선순위 -tags: - - JavaScript - - Operator - - 연산자 - - 우선순위 -translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence ---- -
{{jsSidebar("Operators")}}
- -

연산자 우선순위는 연산자를 실행하는 순서를 결정합니다. 우선순위가 높은 연산자가 먼저 실행됩니다.

- -
{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}
- - - -

우선순위와 결합성

- -

아래와 같이 표현할 수 있는 표현식을 생각해 봅시다. 연산자1과 연산자2의 자리에는 아무 연산자를 넣을 수 있습니다.

- -
a 연산자1 b 연산자2 c
- -

두 연산자의 우선순위(아래 표 참조)가 다를 경우, 우선순위가 높은 연산자가 먼저 실행되고 결합성은 영향을 미치지 않습니다. 아래 예제에서는 덧셈이 곱셈보다 먼저 쓰였음에도 곱셈의 우선순위가 높기 때문에 먼저 실행됩니다.

- -
console.log(3 + 10 * 2);   // 23을 출력
-console.log(3 + (10 * 2)); // 23을 출력, 괄호는 불필요함
-console.log((3 + 10) * 2); // 26을 출력, 괄호로 인해 실행 순서가 바뀜
-
- -

좌결합성(왼쪽에서 오른쪽으로)은 표현식이 (a 연산자1 b) 연산자2 c와 같이, 우결합성(오른쪽에서 왼쪽으로)은 a 연산자1 (b 연산자2 c)와 같이 계산된다는 의미입니다. 대입 연산자는 우결합성이므로 다음과 같은 코드를 작성할 수 있습니다.

- -
a = b = 5; // a = (b = 5);와 같음
-
- -

이때 대입 연산자는 대입된 값을 반환하므로 ab의 값이 5가 됨을 예상할 수 있습니다. 우선 b의 값이 5로 설정되고, 그 다음에는 a의 값이 우변인 b = 5의 반환값 5로 설정됩니다.

- -

다른 예시로, 좌결합성인 다른 산술 연산자와 달리 거듭제곱 연산자 (**)만은 우결합성입니다. 흥미로운 점으로 표현식의 평가는 결합성과 무관하게 항상 왼쪽에서 오른쪽으로 진행됩니다.

- - - - - - - - - - - - - - - - -
코드출력
-
-function echo(name, num) {
-    console.log(name + " 항 평가함");
-    return num;
-}
-// 나눗셈 연산자 (/)에 주목
-console.log(echo("첫째", 6) / echo("둘째", 2));
-
-
-
-첫째 항 평가함
-둘째 항 평가함
-3
-
-
-
-function echo(name, num) {
-    console.log(name + " 항 평가함");
-    return num;
-}
-// 거듭제곱 연산자 (**)에 주목
-console.log(echo("첫째", 2) ** echo("둘째", 3));
-
-
-첫째 항 평가함
-둘째 항 평가함
-8
-
- -

여러 연산자의 우선순위가 같을 때는 결합성을 고려합니다. 위에서와 같이 연산자가 하나이거나 연산자끼리 우선순위가 다를 경우에는 결합성이 결과에 영향을 미치지 않습니다. 아래의 예제에서 같은 종류의 연산자를 여러 번 사용했을 때 결합성이 결과에 영향을 미치는 것을 확인할 수 있습니다.

- - - - - - - - - - - - - - - - - - - - -
코드출력
-
-function echo(name, num) {
-    console.log(name + " 항 평가함");
-    return num;
-}
-// 나눗셈 연산자 (/)에 주목
-console.log(echo("첫째", 6) / echo("둘째", 2) / echo("셋째", 3));
-
-
-
-첫째 항 평가함
-둘째 항 평가함
-셋째 항 평가함
-1
-
-
-
-function echo(name, num) {
-    console.log(name + " 항 평가함");
-    return num;
-}
-// 거듭제곱 연산자 (**)에 주목
-console.log(echo("첫째", 2) ** echo("둘째", 3) ** echo("셋째", 2));
-
-
-
-첫째 항 평가함
-둘째 항 평가함
-셋째 항 평가함
-512
-
-
-
-function echo(name, num) {
-    console.log(name + " 항 평가함");
-    return num;
-}
-// 첫 번째 거듭제곱 연산자 주변의 괄호에 주목
-console.log((echo("첫째", 2) ** echo("둘째", 3)) ** echo("셋째", 2));
-
-
-첫째 항 평가함
-둘째 항 평가함
-셋째 항 평가함
-64
-
- -

위의 예제에서 나눗셈은 좌결합성이므로 6 / 3 / 2(6 / 3) / 2와 같습니다. 한편 거듭제곱은 우결합성이므로 2 ** 3 ** 22 ** (3 ** 2)와 같습니다. 그러므로 (2 ** 3) ** 2는 괄호로 인해 실행 순서가 바뀌기 때문에 위 표와 같이 64로 평가됩니다.

- -

우선순위는 결합성보다 항상 우선하므로, 거듭제곱과 나눗셈을 같이 사용하면 나눗셈보다 거듭제곱이 먼저 계산됩니다. 예를 들어 2 ** 3 / 3 ** 2는 (2 ** 3) / (3 ** 2)와 같으므로 0.8888888888888888로 계산됩니다.

- -

예제

- -
3 > 2 && 2 > 1
-// true를 반환
-
-3 > 2 > 1
-// 3 > 2는 true인데, 부등호 연산자에서 true는 1로 변환되므로
-// true > 1은 1 > 1이 되고, 이는 거짓이다.
-// 괄호를 추가하면 (3 > 2) > 1과 같다.
- -

- -

다음 표는 우선순위 내림차순(21부터 1까지)으로 정렬되어 있습니다.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
우선순위연산자 유형결합성연산자
21{{jsxref("Operators/Grouping", "그룹", "", 1)}}없음( … )
20{{jsxref("Operators/Property_Accessors", "멤버 접근", "#점_표기법", 1)}}좌결합성… . …
{{jsxref("Operators/Property_Accessors", "계산된 멤버 접근","#괄호_표기법", "1")}}좌결합성… [ … ]
{{jsxref("Operators/new","new")}} (매개변수 리스트 존재)없음new … ( … )
-

함수 호출

-
좌결합성… ( )
Optional chaining좌결합성?.
19{{jsxref("Operators/new","new")}} (매개변수 리스트 생략)우결합성new …
18{{jsxref("Operators/Arithmetic_Operators","후위 증가","#Increment", 1)}}없음… ++
{{jsxref("Operators/Arithmetic_Operators","후위 감소","#Decrement", 1)}}… --
17논리 NOT우결합성! …
비트 NOT~ …
단항 양부호+ …
단항 부정- …
전위 증가++ …
전위 감소-- …
{{jsxref("Operators/typeof", "typeof")}}typeof …
{{jsxref("Operators/void", "void")}}void …
{{jsxref("Operators/delete", "delete")}}delete …
{{jsxref("Operators/await", "await")}}await …
16거듭제곱우결합성… ** …
15곱셈좌결합성… * …
나눗셈… / …
나머지… % …
14덧셈좌결합성… + …
뺄셈… - …
13비트 왼쪽 시프트좌결합성… << …
비트 오른쪽 시프트… >> …
비트 부호 없는 오른쪽 시프트… >>> …
12미만좌결합성… < …
이하… <= …
초과… > …
이상… >= …
{{jsxref("Operators/in", "in")}}… in …
{{jsxref("Operators/instanceof", "instanceof")}}… instanceof …
11동등좌결합성… == …
부등… != …
일치… === …
불일치… !== …
10비트 AND좌결합성… & …
9비트 XOR좌결합성… ^ …
8비트 OR좌결합성… | …
7널 병합 연산자좌결합성… ?? …
6논리 AND좌결합성… && …
5논리 OR좌결합성… || …
4조건우결합성… ? … : …
3할당우결합성… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2{{jsxref("Operators/yield", "yield")}}우결합성yield …
{{jsxref("Operators/yield*", "yield*")}}yield* …
1쉼표 / 시퀀스좌결합성… , …
diff --git a/files/ko/web/javascript/reference/statements/default/index.html b/files/ko/web/javascript/reference/statements/default/index.html deleted file mode 100644 index 4fe127b7db..0000000000 --- a/files/ko/web/javascript/reference/statements/default/index.html +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: default -slug: Web/JavaScript/Reference/Statements/default -tags: - - JavaScript - - Keyword - - Reference -translation_of: Web/JavaScript/Reference/Statements/switch -translation_of_original: Web/JavaScript/Reference/Statements/default ---- -
{{jsSidebar("Statements")}}
- -

default 키워드는 {{jsxref("Statements/switch", "switch")}} 구문과 {{jsxref("Statements/export", "export")}} 구문에서 사용할 수 있습니다.

- -
{{EmbedInteractiveExample("pages/js/statement-default.html")}}
- - - -

구문

- -

{{jsxref("Statements/switch", "switch")}} 구문 내에서는 다음과 같이 사용합니다.

- -
switch (expression) {
-  case value1:
-    //Statements executed when the result of expression matches value1
-    [break;]
-  default:
-    //Statements executed when none of the values match the value of the expression
-    [break;]
-}
- -

{{jsxref("Statements/export", "export")}} 구문 내에서는 다음과 같이 사용합니다.

- -
export default nameN 
- -

설명

- -

세부사항을 보려면,

- - - -

예제

- -

switch에서 default 사용

- -

아래 예제에서 expr 이 "오렌지" 또는 "사과"일 때, 프로그램은 값을 "오렌지" 또는 "사과"와 일치시키고 해당 명령문을 실행합니다. 기본(default) 키워드는 다른 경우에 도움이 되며 연관된 명령문을 실행합니다.

- -
switch (expr) {
-  case '오렌지':
-    console.log('오렌지는 1000원입니다.');
-    break;
-  case '사과':
-    console.log('사과는 500원입니다.');
-    break;
-  default:
-    console.log('죄송합니다. ' + expr + '의 재고가 다 떨어졌습니다.');
-}
- -

export에서 default 사용

- -

단일 값을 내보내거나 모듈의 기본 값이 필요한 경우, 기본 내보내기를 사용할 수 있습니다.

- -
// module "my-module.js"
-let cube = function cube(x) {
-  return x * x * x;
-};
-export default cube;
- -

다른 스크립트에서 가져오는 건 간단합니다.

- -
// module "my-module.js"
-import cube from 'my-module';  //default export gave us the liberty to say import cube, instead of import cube from 'my-module'
-console.log(cube(3)); // 27
-
- -

명세

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-switch-statement', 'switch statement')}}{{Spec2('ES6')}}
{{SpecName('ES6', '#sec-exports', 'Exports')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-switch-statement', 'switch statement')}}{{Spec2('ESDraft')}}
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}{{Spec2('ESDraft')}}
- -

브라우저 호환성

- - - -

{{Compat("javascript.statements.default")}}

- -

같이 보기

- - -- cgit v1.2.3-54-g00ecf