From 310fd066e91f454b990372ffa30e803cc8120975 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 12:56:40 +0100 Subject: unslug zh-cn: move --- .../reference/classes/class_elements/index.html | 352 ---------- .../classes/public_class_fields/index.html | 352 ++++++++++ .../errors/cant_assign_to_property/index.html | 52 ++ .../index.html" | 52 -- .../global_objects/array/prototype/index.html | 178 ----- .../arraybuffer/prototype/index.html | 64 -- .../asyncfunction/prototype/index.html | 57 -- .../global_objects/asynciterator/index.html | 119 ---- .../global_objects/boolean/prototype/index.html | 76 --- .../global_objects/dataview/prototype/index.html | 103 --- .../global_objects/date/prototype/index.html | 181 ----- .../global_objects/error/prototype/index.html | 162 ----- .../global_objects/evalerror/prototype/index.html | 85 --- .../global_objects/function/prototype/index.html | 139 ---- .../generatorfunction/prototype/index.html | 65 -- .../intl/datetimeformat/prototype/index.html | 120 ---- .../global_objects/map/prototype/index.html | 131 ---- .../reference/global_objects/math/acosh/index.html | 91 +++ .../index.html" | 91 --- .../global_objects/number/prototype/index.html | 132 ---- .../global_objects/object/prototype/index.html | 195 ------ .../global_objects/promise/prototype/index.html | 116 ---- .../global_objects/proxy/handler/apply/index.html | 117 ---- .../proxy/handler/construct/index.html | 130 ---- .../proxy/handler/defineproperty/index.html | 181 ----- .../proxy/handler/deleteproperty/index.html | 149 ---- .../global_objects/proxy/handler/get/index.html | 177 ----- .../handler/getownpropertydescriptor/index.html | 168 ----- .../proxy/handler/getprototypeof/index.html | 141 ---- .../global_objects/proxy/handler/has/index.html | 176 ----- .../global_objects/proxy/handler/index.html | 77 --- .../proxy/handler/isextensible/index.html | 123 ---- .../proxy/handler/ownkeys/index.html | 193 ------ .../proxy/handler/preventextensions/index.html | 120 ---- .../global_objects/proxy/handler/set/index.html | 125 ---- .../proxy/handler/setprototypeof/index.html | 124 ---- .../global_objects/proxy/proxy/apply/index.html | 117 ++++ .../proxy/proxy/construct/index.html | 130 ++++ .../proxy/proxy/defineproperty/index.html | 181 +++++ .../proxy/proxy/deleteproperty/index.html | 149 ++++ .../global_objects/proxy/proxy/get/index.html | 177 +++++ .../proxy/getownpropertydescriptor/index.html | 168 +++++ .../proxy/proxy/getprototypeof/index.html | 141 ++++ .../global_objects/proxy/proxy/has/index.html | 176 +++++ .../proxy/proxy/isextensible/index.html | 123 ++++ .../global_objects/proxy/proxy/ownkeys/index.html | 193 ++++++ .../proxy/proxy/preventextensions/index.html | 120 ++++ .../global_objects/proxy/proxy/set/index.html | 125 ++++ .../proxy/proxy/setprototypeof/index.html | 124 ++++ .../global_objects/rangeerror/prototype/index.html | 89 --- .../referenceerror/prototype/index.html | 93 --- .../index.html | 134 ++++ .../index.html" | 134 ---- .../global_objects/regexp/prototype/index.html | 153 ----- .../sharedarraybuffer/prototype/index.html | 63 -- .../global_objects/string/prototype/index.html | 187 ----- .../global_objects/string/trimend/index.html | 84 +++ .../global_objects/string/trimleft/index.html | 122 ---- .../global_objects/string/trimright/index.html | 84 --- .../global_objects/string/trimstart/index.html | 122 ++++ .../global_objects/symbol/prototype/index.html | 67 -- .../syntaxerror/prototype/index.html | 133 ---- .../global_objects/typedarray/prototype/index.html | 172 ----- .../global_objects/typeerror/prototype/index.html | 94 --- .../global_objects/urierror/prototype/index.html | 83 --- .../global_objects/weakmap/prototype/index.html | 138 ---- .../global_objects/weakset/prototype/index.html | 115 ---- .../reference/operators/addition/index.html | 79 +++ .../operators/arithmetic_operators/index.html | 302 -------- .../operators/assignment_operators/index.html | 413 ----------- .../reference/operators/async_function/index.html | 98 +++ .../index.html" | 98 --- .../reference/operators/bitwise_and/index.html | 106 +++ .../operators/bitwise_operators/index.html | 756 --------------------- .../operators/comparison_operators/index.html | 278 -------- .../reference/operators/decrement/index.html | 85 +++ .../reference/operators/equality/index.html | 125 ++++ .../reference/operators/logical_and/index.html | 137 ++++ .../operators/logical_operators/index.html | 238 ------- .../operators/optional_chaining/index.html | 202 ++++++ .../operators/pipeline_operator/index.html | 75 ++ .../reference/operators/remainder/index.html | 81 +++ .../operators/\345\217\226\344\275\231/index.html" | 81 --- .../index.html" | 202 ------ .../index.html" | 106 --- .../operators/\347\233\270\345\212\240/index.html" | 79 --- .../operators/\347\233\270\347\255\211/index.html" | 125 ---- .../index.html" | 75 -- .../operators/\350\207\252\345\207\217/index.html" | 85 --- .../index.html" | 137 ---- .../javascript/reference/reserved_words/index.html | 82 --- .../reference/statements/default/index.html | 120 ---- .../reference/template_literals/index.html | 261 +++++++ .../reference/template_strings/index.html | 261 ------- 94 files changed, 4008 insertions(+), 9584 deletions(-) delete mode 100644 files/zh-cn/web/javascript/reference/classes/class_elements/index.html create mode 100644 files/zh-cn/web/javascript/reference/classes/public_class_fields/index.html create mode 100644 files/zh-cn/web/javascript/reference/errors/cant_assign_to_property/index.html delete mode 100644 "files/zh-cn/web/javascript/reference/errors/\344\270\215\350\203\275\346\267\273\345\212\240\345\261\236\346\200\247/index.html" delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/array/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/arraybuffer/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/asyncfunction/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/asynciterator/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/boolean/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/dataview/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/date/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/error/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/evalerror/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/function/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/generatorfunction/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/map/prototype/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/math/acosh/index.html delete mode 100644 "files/zh-cn/web/javascript/reference/global_objects/math/\345\217\215\345\217\214\346\233\262\344\275\231\345\274\246\345\200\274/index.html" delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/number/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/object/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/promise/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/handler/apply/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/handler/construct/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/handler/defineproperty/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/handler/deleteproperty/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/handler/get/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/handler/getownpropertydescriptor/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/handler/getprototypeof/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/handler/has/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/handler/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/handler/isextensible/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/handler/ownkeys/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/handler/preventextensions/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/handler/set/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/handler/setprototypeof/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/apply/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/construct/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/defineproperty/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/deleteproperty/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/get/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/getownpropertydescriptor/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/getprototypeof/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/has/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/isextensible/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/ownkeys/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/preventextensions/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/set/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/setprototypeof/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/rangeerror/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/referenceerror/prototype/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/reflect/comparing_reflect_and_object_methods/index.html delete mode 100644 "files/zh-cn/web/javascript/reference/global_objects/reflect/\346\257\224\350\276\203_reflect_\345\222\214_object_\346\226\271\346\263\225/index.html" delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/regexp/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/prototype/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/trimend/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/trimleft/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/trimright/index.html create mode 100644 files/zh-cn/web/javascript/reference/global_objects/string/trimstart/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/symbol/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/syntaxerror/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/typedarray/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/typeerror/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/urierror/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/weakmap/prototype/index.html delete mode 100644 files/zh-cn/web/javascript/reference/global_objects/weakset/prototype/index.html create mode 100644 files/zh-cn/web/javascript/reference/operators/addition/index.html delete mode 100644 files/zh-cn/web/javascript/reference/operators/arithmetic_operators/index.html delete mode 100644 files/zh-cn/web/javascript/reference/operators/assignment_operators/index.html create mode 100644 files/zh-cn/web/javascript/reference/operators/async_function/index.html delete mode 100644 "files/zh-cn/web/javascript/reference/operators/async\345\205\201\350\256\270\345\243\260\346\230\216\344\270\200\344\270\252\345\207\275\346\225\260\344\270\272\344\270\200\344\270\252\345\214\205\345\220\253\345\274\202\346\255\245\346\223\215\344\275\234\347\232\204\345\207\275\346\225\260/index.html" create mode 100644 files/zh-cn/web/javascript/reference/operators/bitwise_and/index.html delete mode 100644 files/zh-cn/web/javascript/reference/operators/bitwise_operators/index.html delete mode 100644 files/zh-cn/web/javascript/reference/operators/comparison_operators/index.html create mode 100644 files/zh-cn/web/javascript/reference/operators/decrement/index.html create mode 100644 files/zh-cn/web/javascript/reference/operators/equality/index.html create mode 100644 files/zh-cn/web/javascript/reference/operators/logical_and/index.html delete mode 100644 files/zh-cn/web/javascript/reference/operators/logical_operators/index.html create mode 100644 files/zh-cn/web/javascript/reference/operators/optional_chaining/index.html create mode 100644 files/zh-cn/web/javascript/reference/operators/pipeline_operator/index.html create mode 100644 files/zh-cn/web/javascript/reference/operators/remainder/index.html delete mode 100644 "files/zh-cn/web/javascript/reference/operators/\345\217\226\344\275\231/index.html" delete mode 100644 "files/zh-cn/web/javascript/reference/operators/\345\217\257\351\200\211\351\223\276/index.html" delete mode 100644 "files/zh-cn/web/javascript/reference/operators/\346\214\211\344\275\215\344\270\216/index.html" delete mode 100644 "files/zh-cn/web/javascript/reference/operators/\347\233\270\345\212\240/index.html" delete mode 100644 "files/zh-cn/web/javascript/reference/operators/\347\233\270\347\255\211/index.html" delete mode 100644 "files/zh-cn/web/javascript/reference/operators/\347\256\241\351\201\223\346\223\215\344\275\234\347\254\246/index.html" delete mode 100644 "files/zh-cn/web/javascript/reference/operators/\350\207\252\345\207\217/index.html" delete mode 100644 "files/zh-cn/web/javascript/reference/operators/\351\200\273\350\276\221\345\222\214/index.html" delete mode 100644 files/zh-cn/web/javascript/reference/reserved_words/index.html delete mode 100644 files/zh-cn/web/javascript/reference/statements/default/index.html create mode 100644 files/zh-cn/web/javascript/reference/template_literals/index.html delete mode 100644 files/zh-cn/web/javascript/reference/template_strings/index.html (limited to 'files/zh-cn/web/javascript/reference') diff --git a/files/zh-cn/web/javascript/reference/classes/class_elements/index.html b/files/zh-cn/web/javascript/reference/classes/class_elements/index.html deleted file mode 100644 index fb8c618a9b..0000000000 --- a/files/zh-cn/web/javascript/reference/classes/class_elements/index.html +++ /dev/null @@ -1,352 +0,0 @@ ---- -title: 类元素 -slug: Web/JavaScript/Reference/Classes/Class_elements -tags: - - Class - - JavaScript - - 类 -translation_of: Web/JavaScript/Reference/Classes/Public_class_fields ---- -
{{JsSidebar("Classes")}}
- -
公有(public)和私有(private)字段声明是一个JavaScript标准委员会TC39提议的试验性功能 (第3阶段)。这项功能在浏览器中的支持还受限,但你可以通过Babel等构建系统来使用它。参见下面的兼容性信息
- -

公有字段

- -

静态公有字段和实例公有字段都是可编辑的,可遍历的,可配置的。它们本身不同于私有对应值(private counterparts)的是,它们参与原型的继承。

- -

静态公有字段

- -

静态公有字段在你想要创建一个只在每个类里面只存在一份,而不会存在于你创建的每个类的实例中的属性时可以用到。你可以用它存放缓存数据、固定结构数据或者其他你不想在所有实例都复制一份的数据。

- -

静态公有字段是使用关键字 static 声明的。我们在声明一个类的时候,使用Object.defineProperty方法将静态公有字段添加到类的构造函数中。在类被声明之后,可以从类的构造函数访问静态公有字段。

- -
class ClassWithStaticField {
-  static staticField = 'static field';
-}
-
-console.log(ClassWithStaticField.staticField);
-// 预期输出值: "static field"​
-
- -

没有设定初始化程序的字段将默认被初始化为undefined

- -
class ClassWithStaticField {
-  static staticField;
-}
-
-console.assert(ClassWithStaticField.hasOwnProperty('staticField'));
-console.log(ClassWithStaticField.staticField);
-// 预期输出值: "undefined"
- -

静态公有字段不会在子类里重复初始化,但我们可以通过原型链访问它们。

- -
class ClassWithStaticField {
-  static baseStaticField = 'base field';
-}
-
-class SubClassWithStaticField extends ClassWithStaticField {
-  static subStaticField = 'sub class field';
-}
-
-console.log(SubClassWithStaticField.subStaticField);
-// 预期输出值: "sub class field"
-
-console.log(SubClassWithStaticField.baseStaticField);
-// 预期输出值: "base field"
- -

当初始化字段时,this指向的是类的构造函数。你可以通过名字引用构造函数,并使用super获取到存在的超类构造函数。

- -
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);
-// 预期输出值: "base static field"
-
-console.log(SubClassWithStaticField.subStaticField);
-// 预期输出值: "base static method output"
-
- -

公有实例字段

- -

公有实例字段存在于类的每一个实例中。通过声明一个公有字段,我们可以确保该字段一直存在,而类的定义则会更加像是自我描述。

- -

公有实例字段可以在基类的构造过程中(构造函数主体运行前)使用Object.defineProperty添加,也可以在子类构造函数中的super()函数结束后添加。

- -
class ClassWithInstanceField {
-  instanceField = 'instance field';
-}
-
-const instance = new ClassWithInstanceField();
-console.log(instance.instanceField);
-// 预期输出值: "instance field"
- -

没有设定初始化程序的字段将默认被初始化为undefined

- -
class ClassWithInstanceField {
-  instanceField;
-}
-
-const instance = new ClassWithInstanceField();
-console.assert(instance.hasOwnProperty('instanceField'));
-console.log(instance.instanceField);
-// 预期输出值: "undefined"
- -

和属性(properties)一样,字段名可以由计算得出。

- -
const PREFIX = 'prefix';
-
-class ClassWithComputedFieldName {
-    [`${PREFIX}Field`] = 'prefixed field';
-}
-
-const instance = new ClassWithComputedFieldName();
-console.log(instance.prefixField);
-// 预期输出值: "prefixed field"
- -

当初始化字段时,this指向的是类正在构造中的实例。和公共实例方法相同的是:你可以在子类中使用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);
-// 预期输出值: "base field"
-
-console.log(sub.subInstanceField);
-// 预期输出值: "base method output"
- -

公共方法

- -

静态公共方法

- -

关键字static将为一个类定义一个静态方法。静态方法不会在实例中被调用,而只会被类本身调用。它们经常是工具函数,比如用来创建或者复制对象。

- -

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

- - - -

静态方法是在类的赋值阶段用Object.defineProperty方法添加到类中的。静态方法是可编辑的、不可遍历的和可配置的。

- -

公共实例方法

- -

正如其名,公共实例方法是可以在类的实例中使用的。

- -
class ClassWithPublicInstanceMethod {
-  publicMethod() {
-    return 'hello world';
-  }
-}
-
-const instance = new ClassWithPublicInstanceMethod();
-console.log(instance.publicMethod());
-// 预期输出值: "hello worl​d"
- -

公共实例方法是在类的赋值阶段用Object.defineProperty方法添加到类中的。静态方法是可编辑的、不可遍历的和可配置的。

- -

你可以使用生成器(generator)、异步和异步生成器方法。

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

在实例的方法中,this指向的是实例本身,你可以使用super访问到超类的原型,由此你可以调用超类的方法。

- -
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());
-// 预期输出值: "hello worl​d"
-
- -

gettersetter是和类的属性绑定的特殊方法,分别会在其绑定的属性被取值、赋值时调用。使用getset句法定义实例的公共gettersetter

- -
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);
-// 预期输出值: "hello cake"
-
- -

私有字段

- -

静态私有字段

- -

静态私有字段可以在类声明本身内部的构造函数上被访问到。

- -

静态变量只能被静态方法访问的限制依然存在。

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

静态私有字段是在类赋值的时候被添加到类构造函数中的。

- -

静态私有字段有一个来源限制。只有定义静态私有字段的类可以访问该字段。这在使用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);
-
- -

私有实例字段

- -

私有实例字段是通过# names句型(读作“哈希名称”)声明的,即为识别符加一个前缀“#”。“#”是名称的一部分,也用于访问和声明。

- -

封装是语言强制实施的。引用不在作用域内的 # names 是语法错误。

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

私有方法

- -

静态私有方法

- -

和静态公共方法一样,静态私有方法也是在类里面而非实例中调用的。和静态私有字段一样,它们也只能在类的声明中访问。

- -

你可以使用生成器(generator)、异步和异步生成器方法。

- -

静态私有方法可以是生成器、异步或者异步生成器函数。

- -
class ClassWithPrivateStaticMethod {
-    static #privateStaticMethod() {
-        return 42;
-    }
-
-    static publicStaticMethod() {
-        return ClassWithPrivateStaticMethod.#privateStaticMethod();
-    }
-}
-
-assert(ClassWithPrivateStaticMethod.publicStaticMethod() === 42);
-
- -

私有实例方法

- -

私有实例方法在类的实例中可用,它的访问方式的限制和私有实例字段相同。

- -
class ClassWithPrivateMethod {
-  #privateMethod() {
-    return 'hello world';
-  }
-
-  getPrivateMessage() {
-      return #privateMethod();
-  }
-}
-
-const instance = new ClassWithPrivateMethod();
-console.log(instance.getPrivateMessage());
-// 预期输出值: "hello worl​d"
- -

私有实例方法可以是生成器、异步或者异步生成器函数。私有gettersetter也是可能的:

- -
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();
-// 预期输出值: "✨hello worl​d✨"
-
- -

浏览器兼容性

- -

公共类字段

- - - -

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

- -

私有类字段

- - - -

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

- -

另请参考:

- - diff --git a/files/zh-cn/web/javascript/reference/classes/public_class_fields/index.html b/files/zh-cn/web/javascript/reference/classes/public_class_fields/index.html new file mode 100644 index 0000000000..fb8c618a9b --- /dev/null +++ b/files/zh-cn/web/javascript/reference/classes/public_class_fields/index.html @@ -0,0 +1,352 @@ +--- +title: 类元素 +slug: Web/JavaScript/Reference/Classes/Class_elements +tags: + - Class + - JavaScript + - 类 +translation_of: Web/JavaScript/Reference/Classes/Public_class_fields +--- +
{{JsSidebar("Classes")}}
+ +
公有(public)和私有(private)字段声明是一个JavaScript标准委员会TC39提议的试验性功能 (第3阶段)。这项功能在浏览器中的支持还受限,但你可以通过Babel等构建系统来使用它。参见下面的兼容性信息
+ +

公有字段

+ +

静态公有字段和实例公有字段都是可编辑的,可遍历的,可配置的。它们本身不同于私有对应值(private counterparts)的是,它们参与原型的继承。

+ +

静态公有字段

+ +

静态公有字段在你想要创建一个只在每个类里面只存在一份,而不会存在于你创建的每个类的实例中的属性时可以用到。你可以用它存放缓存数据、固定结构数据或者其他你不想在所有实例都复制一份的数据。

+ +

静态公有字段是使用关键字 static 声明的。我们在声明一个类的时候,使用Object.defineProperty方法将静态公有字段添加到类的构造函数中。在类被声明之后,可以从类的构造函数访问静态公有字段。

+ +
class ClassWithStaticField {
+  static staticField = 'static field';
+}
+
+console.log(ClassWithStaticField.staticField);
+// 预期输出值: "static field"​
+
+ +

没有设定初始化程序的字段将默认被初始化为undefined

+ +
class ClassWithStaticField {
+  static staticField;
+}
+
+console.assert(ClassWithStaticField.hasOwnProperty('staticField'));
+console.log(ClassWithStaticField.staticField);
+// 预期输出值: "undefined"
+ +

静态公有字段不会在子类里重复初始化,但我们可以通过原型链访问它们。

+ +
class ClassWithStaticField {
+  static baseStaticField = 'base field';
+}
+
+class SubClassWithStaticField extends ClassWithStaticField {
+  static subStaticField = 'sub class field';
+}
+
+console.log(SubClassWithStaticField.subStaticField);
+// 预期输出值: "sub class field"
+
+console.log(SubClassWithStaticField.baseStaticField);
+// 预期输出值: "base field"
+ +

当初始化字段时,this指向的是类的构造函数。你可以通过名字引用构造函数,并使用super获取到存在的超类构造函数。

+ +
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);
+// 预期输出值: "base static field"
+
+console.log(SubClassWithStaticField.subStaticField);
+// 预期输出值: "base static method output"
+
+ +

公有实例字段

+ +

公有实例字段存在于类的每一个实例中。通过声明一个公有字段,我们可以确保该字段一直存在,而类的定义则会更加像是自我描述。

+ +

公有实例字段可以在基类的构造过程中(构造函数主体运行前)使用Object.defineProperty添加,也可以在子类构造函数中的super()函数结束后添加。

+ +
class ClassWithInstanceField {
+  instanceField = 'instance field';
+}
+
+const instance = new ClassWithInstanceField();
+console.log(instance.instanceField);
+// 预期输出值: "instance field"
+ +

没有设定初始化程序的字段将默认被初始化为undefined

+ +
class ClassWithInstanceField {
+  instanceField;
+}
+
+const instance = new ClassWithInstanceField();
+console.assert(instance.hasOwnProperty('instanceField'));
+console.log(instance.instanceField);
+// 预期输出值: "undefined"
+ +

和属性(properties)一样,字段名可以由计算得出。

+ +
const PREFIX = 'prefix';
+
+class ClassWithComputedFieldName {
+    [`${PREFIX}Field`] = 'prefixed field';
+}
+
+const instance = new ClassWithComputedFieldName();
+console.log(instance.prefixField);
+// 预期输出值: "prefixed field"
+ +

当初始化字段时,this指向的是类正在构造中的实例。和公共实例方法相同的是:你可以在子类中使用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);
+// 预期输出值: "base field"
+
+console.log(sub.subInstanceField);
+// 预期输出值: "base method output"
+ +

公共方法

+ +

静态公共方法

+ +

关键字static将为一个类定义一个静态方法。静态方法不会在实例中被调用,而只会被类本身调用。它们经常是工具函数,比如用来创建或者复制对象。

+ +

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

+ + + +

静态方法是在类的赋值阶段用Object.defineProperty方法添加到类中的。静态方法是可编辑的、不可遍历的和可配置的。

+ +

公共实例方法

+ +

正如其名,公共实例方法是可以在类的实例中使用的。

+ +
class ClassWithPublicInstanceMethod {
+  publicMethod() {
+    return 'hello world';
+  }
+}
+
+const instance = new ClassWithPublicInstanceMethod();
+console.log(instance.publicMethod());
+// 预期输出值: "hello worl​d"
+ +

公共实例方法是在类的赋值阶段用Object.defineProperty方法添加到类中的。静态方法是可编辑的、不可遍历的和可配置的。

+ +

你可以使用生成器(generator)、异步和异步生成器方法。

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

在实例的方法中,this指向的是实例本身,你可以使用super访问到超类的原型,由此你可以调用超类的方法。

+ +
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());
+// 预期输出值: "hello worl​d"
+
+ +

gettersetter是和类的属性绑定的特殊方法,分别会在其绑定的属性被取值、赋值时调用。使用getset句法定义实例的公共gettersetter

+ +
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);
+// 预期输出值: "hello cake"
+
+ +

私有字段

+ +

静态私有字段

+ +

静态私有字段可以在类声明本身内部的构造函数上被访问到。

+ +

静态变量只能被静态方法访问的限制依然存在。

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

静态私有字段是在类赋值的时候被添加到类构造函数中的。

+ +

静态私有字段有一个来源限制。只有定义静态私有字段的类可以访问该字段。这在使用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);
+
+ +

私有实例字段

+ +

私有实例字段是通过# names句型(读作“哈希名称”)声明的,即为识别符加一个前缀“#”。“#”是名称的一部分,也用于访问和声明。

+ +

封装是语言强制实施的。引用不在作用域内的 # names 是语法错误。

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

私有方法

+ +

静态私有方法

+ +

和静态公共方法一样,静态私有方法也是在类里面而非实例中调用的。和静态私有字段一样,它们也只能在类的声明中访问。

+ +

你可以使用生成器(generator)、异步和异步生成器方法。

+ +

静态私有方法可以是生成器、异步或者异步生成器函数。

+ +
class ClassWithPrivateStaticMethod {
+    static #privateStaticMethod() {
+        return 42;
+    }
+
+    static publicStaticMethod() {
+        return ClassWithPrivateStaticMethod.#privateStaticMethod();
+    }
+}
+
+assert(ClassWithPrivateStaticMethod.publicStaticMethod() === 42);
+
+ +

私有实例方法

+ +

私有实例方法在类的实例中可用,它的访问方式的限制和私有实例字段相同。

+ +
class ClassWithPrivateMethod {
+  #privateMethod() {
+    return 'hello world';
+  }
+
+  getPrivateMessage() {
+      return #privateMethod();
+  }
+}
+
+const instance = new ClassWithPrivateMethod();
+console.log(instance.getPrivateMessage());
+// 预期输出值: "hello worl​d"
+ +

私有实例方法可以是生成器、异步或者异步生成器函数。私有gettersetter也是可能的:

+ +
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();
+// 预期输出值: "✨hello worl​d✨"
+
+ +

浏览器兼容性

+ +

公共类字段

+ + + +

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

+ +

私有类字段

+ + + +

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

+ +

另请参考:

+ + diff --git a/files/zh-cn/web/javascript/reference/errors/cant_assign_to_property/index.html b/files/zh-cn/web/javascript/reference/errors/cant_assign_to_property/index.html new file mode 100644 index 0000000000..cceeb330c4 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/errors/cant_assign_to_property/index.html @@ -0,0 +1,52 @@ +--- +title: 'TypeError: can''t assign to property "x" on "y": not an object' +slug: Web/JavaScript/Reference/Errors/不能添加属性 +translation_of: Web/JavaScript/Reference/Errors/Cant_assign_to_property +--- +
{{jsSidebar("Errors")}}
+ +

信息

+ +
TypeError: can't assign to property "x" on {y}: not an object (Firefox)
+TypeError: Cannot create property 'x' on {y} (Chrome)
+
+ +

错误类型

+ +

{{jsxref("TypeError")}}.

+ +

原因

+ +

在 {{jsxref("Strict_mode")}}下, 当试图给一个{{Glossary("symbol")}},{{Glossary("string")}},{{Glossary("number")}}或者一个{{Glossary("boolean")}}类型的数据创建一个属性时就会报 {{jsxref("TypeError")}}, 任何 {{Glossary("Primitive")}} 值都不允许有{{Glossary("property/JavaScript", "property")}}.

+ +

这个问题可能是由一个错误的值被放在了一个错误的地方导致的, 或者预期{{jsxref("String")}}或{{jsxref("Number")}}的对象变体

+ +

 

+ +

示例

+ +

错误的情况

+ +
'use strict';
+
+var foo = "my string";
+// 下面这行代码在非严格模式下不会执行.
+foo.bar = {}; // TypeError: can't assign to property "bar" on "my string": not an object
+
+ +

如何正确使用

+ +

有两种方式, 第一种修复这部分代码阻止{{Glossary("primitive")}}被用于这种情况, 或者可以通过使用对象构造器创建来修复.

+ +
'use strict';
+
+var foo = new String("my string");
+foo.bar = {};
+
+ +

页面相关

+ + diff --git "a/files/zh-cn/web/javascript/reference/errors/\344\270\215\350\203\275\346\267\273\345\212\240\345\261\236\346\200\247/index.html" "b/files/zh-cn/web/javascript/reference/errors/\344\270\215\350\203\275\346\267\273\345\212\240\345\261\236\346\200\247/index.html" deleted file mode 100644 index cceeb330c4..0000000000 --- "a/files/zh-cn/web/javascript/reference/errors/\344\270\215\350\203\275\346\267\273\345\212\240\345\261\236\346\200\247/index.html" +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: 'TypeError: can''t assign to property "x" on "y": not an object' -slug: Web/JavaScript/Reference/Errors/不能添加属性 -translation_of: Web/JavaScript/Reference/Errors/Cant_assign_to_property ---- -
{{jsSidebar("Errors")}}
- -

信息

- -
TypeError: can't assign to property "x" on {y}: not an object (Firefox)
-TypeError: Cannot create property 'x' on {y} (Chrome)
-
- -

错误类型

- -

{{jsxref("TypeError")}}.

- -

原因

- -

在 {{jsxref("Strict_mode")}}下, 当试图给一个{{Glossary("symbol")}},{{Glossary("string")}},{{Glossary("number")}}或者一个{{Glossary("boolean")}}类型的数据创建一个属性时就会报 {{jsxref("TypeError")}}, 任何 {{Glossary("Primitive")}} 值都不允许有{{Glossary("property/JavaScript", "property")}}.

- -

这个问题可能是由一个错误的值被放在了一个错误的地方导致的, 或者预期{{jsxref("String")}}或{{jsxref("Number")}}的对象变体

- -

 

- -

示例

- -

错误的情况

- -
'use strict';
-
-var foo = "my string";
-// 下面这行代码在非严格模式下不会执行.
-foo.bar = {}; // TypeError: can't assign to property "bar" on "my string": not an object
-
- -

如何正确使用

- -

有两种方式, 第一种修复这部分代码阻止{{Glossary("primitive")}}被用于这种情况, 或者可以通过使用对象构造器创建来修复.

- -
'use strict';
-
-var foo = new String("my string");
-foo.bar = {};
-
- -

页面相关

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/prototype/index.html deleted file mode 100644 index 31d65bf734..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/array/prototype/index.html +++ /dev/null @@ -1,178 +0,0 @@ ---- -title: Array.prototype -slug: Web/JavaScript/Reference/Global_Objects/Array/prototype -tags: - - Array.prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Array/prototype ---- -
{{JSRef}}
- -

Array.prototype  属性表示 {{jsxref("Array")}} 构造函数的原型,并允许您向所有Array对象添加新的属性和方法。

- -
/*
-如果JavaScript本身不提供 first() 方法,
-添加一个返回数组的第一个元素的新方法。
-*/
-
-if(!Array.prototype.first) {
-    Array.prototype.first = function() {
-        console.log(`如果JavaScript本身不提供 first() 方法,
-添加一个返回数组的第一个元素的新方法。`);
-        return this[0];
-    }
-}
-
- -

描述

- -

{{jsxref("Array")}}实例继承自 Array.prototype 。与所有构造函数一样,您可以更改构造函数的原型对象,以对所有 {{jsxref("Array")}} 实例进行更改。例如,可以添加新方法和属性以扩展所有Array对象。这用于 {{Glossary("Polyfill", "polyfilling")}}, 例如。

- -

鲜为人知的事实:Array.prototype 本身也是一个 {{jsxref("Array")}}。

- -
Array.isArray(Array.prototype);
-// true
-
- -

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

- -

属性

- -
-
Array.prototype.constructor
-
所有的数组实例都继承了这个属性,它的值就是 {{jsxref("Array")}},表明了所有的数组都是由 {{jsxref("Array")}} 构造出来的。
-
{{jsxref("Array.prototype.length")}}
-
上面说了,因为 Array.prototype 也是个数组,所以它也有 length 属性,这个值为 0,因为它是个空数组。
-
- -

方法

- -

会改变自身的方法

- -

下面的这些方法会改变调用它们的对象自身的值:

- -
-
{{jsxref("Array.prototype.copyWithin()")}} {{experimental_inline}}
-
在数组内部,将一段元素序列拷贝到另一段元素序列上,覆盖原有的值。
-
{{jsxref("Array.prototype.fill()")}} {{experimental_inline}}
-
将数组中指定区间的所有元素的值,都替换成某个固定的值。
-
{{jsxref("Array.prototype.pop()")}}
-
删除数组的最后一个元素,并返回这个元素。
-
{{jsxref("Array.prototype.push()")}}
-
在数组的末尾增加一个或多个元素,并返回数组的新长度。
-
{{jsxref("Array.prototype.reverse()")}}
-
颠倒数组中元素的排列顺序,即原先的第一个变为最后一个,原先的最后一个变为第一个。
-
{{jsxref("Array.prototype.shift()")}}
-
删除数组的第一个元素,并返回这个元素。
-
{{jsxref("Array.prototype.sort()")}}
-
对数组元素进行排序,并返回当前数组。
-
{{jsxref("Array.prototype.splice()")}}
-
在任意的位置给数组添加或删除任意个元素。
-
{{jsxref("Array.prototype.unshift()")}}
-
在数组的开头增加一个或多个元素,并返回数组的新长度。
-
- -

不会改变自身的方法

- -

下面的这些方法绝对不会改变调用它们的对象的值,只会返回一个新的数组或者返回一个其它的期望值。

- -
-
{{jsxref("Array.prototype.concat()")}}
-
返回一个由当前数组和其它若干个数组或者若干个非数组值组合而成的新数组。
-
{{jsxref("Array.prototype.includes()")}} {{experimental_inline}}
-
判断当前数组是否包含某指定的值,如果是返回 true,否则返回 false
-
{{jsxref("Array.prototype.join()")}}
-
连接所有数组元素组成一个字符串。
-
{{jsxref("Array.prototype.slice()")}}
-
抽取当前数组中的一段元素组合成一个新数组。
-
{{jsxref("Array.prototype.toSource()")}} {{non-standard_inline}}
-
返回一个表示当前数组字面量的字符串。遮蔽了原型链上的 {{jsxref("Object.prototype.toSource()")}} 方法。
-
{{jsxref("Array.prototype.toString()")}}
-
返回一个由所有数组元素组合而成的字符串。遮蔽了原型链上的 {{jsxref("Object.prototype.toString()")}} 方法。
-
{{jsxref("Array.prototype.toLocaleString()")}}
-
返回一个由所有数组元素组合而成的本地化后的字符串。遮蔽了原型链上的 {{jsxref("Object.prototype.toLocaleString()")}} 方法。
-
{{jsxref("Array.prototype.indexOf()")}}
-
返回数组中第一个与指定值相等的元素的索引,如果找不到这样的元素,则返回 -1。
-
{{jsxref("Array.prototype.lastIndexOf()")}}
-
返回数组中最后一个(从右边数第一个)与指定值相等的元素的索引,如果找不到这样的元素,则返回 -1。
-
- -

遍历方法

- -

在下面的众多遍历方法中,有很多方法都需要指定一个回调函数作为参数。在每一个数组元素都分别执行完回调函数之前,数组的length属性会被缓存在某个地方,所以,如果你在回调函数中为当前数组添加了新的元素,那么那些新添加的元素是不会被遍历到的。此外,如果在回调函数中对当前数组进行了其它修改,比如改变某个元素的值或者删掉某个元素,那么随后的遍历操作可能会受到未预期的影响。总之,不要尝试在遍历过程中对原数组进行任何修改,虽然规范对这样的操作进行了详细的定义,但为了可读性和可维护性,请不要这样做。

- -
-
{{jsxref("Array.prototype.forEach()")}}
-
为数组中的每个元素执行一次回调函数。
-
{{jsxref("Array.prototype.entries()")}} {{experimental_inline}}
-
返回一个数组迭代器对象,该迭代器会包含所有数组元素的键值对。
-
{{jsxref("Array.prototype.every()")}}
-
如果数组中的每个元素都满足测试函数,则返回 true,否则返回 false。
-
{{jsxref("Array.prototype.some()")}}
-
如果数组中至少有一个元素满足测试函数,则返回 true,否则返回 false。
-
{{jsxref("Array.prototype.filter()")}}
-
将所有在过滤函数中返回 true 的数组元素放进一个新数组中并返回。
-
{{jsxref("Array.prototype.find()")}} {{experimental_inline}}
-
找到第一个满足测试函数的元素并返回那个元素的值,如果找不到,则返回 undefined
-
{{jsxref("Array.prototype.findIndex()")}} {{experimental_inline}}
-
找到第一个满足测试函数的元素并返回那个元素的索引,如果找不到,则返回 -1
-
{{jsxref("Array.prototype.keys()")}} {{experimental_inline}}
-
返回一个数组迭代器对象,该迭代器会包含所有数组元素的键。
-
{{jsxref("Array.prototype.map()")}}
-
返回一个由回调函数的返回值组成的新数组。
-
{{jsxref("Array.prototype.reduce()")}}
-
从左到右为每个数组元素执行一次回调函数,并把上次回调函数的返回值放在一个暂存器中传给下次回调函数,并返回最后一次回调函数的返回值。
-
{{jsxref("Array.prototype.reduceRight()")}}
-
从右到左为每个数组元素执行一次回调函数,并把上次回调函数的返回值放在一个暂存器中传给下次回调函数,并返回最后一次回调函数的返回值。
-
{{jsxref("Array.prototype.values()")}} {{experimental_inline}}
-
返回一个数组迭代器对象,该迭代器会包含所有数组元素的值。
-
{{jsxref("Array.prototype.@@iterator()", "Array.prototype[@@iterator]()")}} {{experimental_inline}}
-
和上面的 values() 方法是同一个函数。
-
- -

通用方法

- -

在 JavaScript 中,很多的数组方法被故意设计成是通用的。也就是说,那些看起来像是数组的对象(类数组对象),即拥有一个 length 属性,以及对应的索引属性(也就是数字类型的属性,比如 obj[5])的非数组对象也是可以调用那些数组方法的。其中一些数组方法,比如说 {{jsxref("Array.join", "join")}} 方法,它们只会单纯的读取当前对象的 length 属性和索引属性的值,并不会尝试去改变这些属性的值。而另外一些数组方法,比如说 {{jsxref("Array.reverse", "reverse")}} 方法,它们会尝试修改那些属性的值,因此,如果当前对象是个 {{jsxref("String")}} 对象,那么这些方法在执行时就会报错,因为字符串对象的 length 属性和索引属性都是只读的。

- -

规范

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4.3.1', 'Array.prototype')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype', 'Array.prototype')}}{{Spec2('ES6')}}
- -

浏览器兼容性

- -
-
- - -

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

-
-
- -

相关链接

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/prototype/index.html deleted file mode 100644 index 92909dbef7..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/prototype/index.html +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: ArrayBuffer.prototype -slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype -tags: - - ArrayBuffer -translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer -translation_of_original: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype ---- -
{{JSRef}}
- -

ArrayBuffer.prototype属性表示{{jsxref("ArrayBuffer")}}对象的原型。

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

描述

- -

ArrayBuffer 实例继承自ArrayBuffer.prototype。对所有的构造函数来说,你可以通过改变构造函数的原型对象来改变所有的ArrayBuffer实例。

- -

属性

- -
-
ArrayBuffer.prototype.constructor
-
指定函数,它创建一个对象的原型。其初始值是标准ArrayBuffer内置构造函数。
-
{{jsxref("ArrayBuffer.prototype.byteLength")}} {{readonlyInline}}
-
数组的字节大小。在数组创建时确定,并且不可变更。只读
-
- -

方法

- -
-
{{jsxref("ArrayBuffer.prototype.slice()")}}
-
返回一个新的 ArrayBuffer ,它的内容是这个 ArrayBuffer 的字节副本,从begin(包括),到end(不包括)。如果begin或end是负数,则指的是从数组末尾开始的索引,而不是从头开始。
-
- -

规范

- - - - - - - - - - - - - - -
规范状态备注
{{SpecName('ES6', '#sec-arraybuffer.prototype', 'ArrayBuffer.prototype')}}{{Spec2('ES6')}}初始定义
- -

浏览器兼容性

- - - -

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

- -

相关链接

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/asyncfunction/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/asyncfunction/prototype/index.html deleted file mode 100644 index 9a8678680a..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/asyncfunction/prototype/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: AsyncFunction.prototype -slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype ---- -
{{JSRef}}
- -

AsyncFunction.prototype 属性表示 {{jsxref("AsyncFunction")}} 的原型对象。

- -

描述

- -

{{jsxref("AsyncFunction")}} 对象继承自 AsyncFunction.prototypeAsyncFunction.prototype 不能被修改。

- -

属性

- -
-
AsyncFunction.constructor
-
默认值为 {{jsxref("AsyncFunction")}}。
-
AsyncFunction.prototype[@@toStringTag]
-
返回 "AsyncFunction"。
-
- -

规范

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-constructor-prototype', 'AsyncFunction.prototype')}}{{Spec2('ESDraft')}}最初定义在ES2017.
- -

兼容性

- -
-
- - -

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

-
-
- -

参见

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/asynciterator/index.html b/files/zh-cn/web/javascript/reference/global_objects/asynciterator/index.html deleted file mode 100644 index 9c14e462bd..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/asynciterator/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: AsyncIterator -slug: Web/JavaScript/Reference/Global_Objects/AsyncIterator -tags: - - 异步迭代器 - - 类 -translation_of: Web/JavaScript/Reference/Global_Objects/AsyncIterator ---- -

{{JSRef}}{{Draft}}

- -

AsyncIterator 全局对象是一个提供辅助方法的抽象类,与暴露在{{JSxRef("Array")}} 实例上的那些类似。

- -

构造函数

- -
-
{{JSxRef("AsyncIterator.AsyncIterator", "AsyncIterator()")}} 
-
一个抽象构造函数,仅能够通过 {{JSxRef("Operators/super", "super()")}} 来调用。
-
- -

属性

- -
-
AsyncIterator.prototype
-
%AsyncIteratorPrototype% 内部对象。
-
- -

方法

- -
-
{{JSxRef("AsyncIterator.from()")}} 
-
等同于在传入的对象上调用 @@asyncIterator 。
-
- -

AsyncIterator 原型

- -

原型属性

- -
-
AsyncIterator.prototype.constructor
-
指定创建对的象原型的函数.
-
AsyncIterator.prototype[@@toStringTag] 
-
字符串 "Iterator".
-
- -

原型方法

- -
-
{{JSxRef("AsyncIterator.prototype.map()")}} 
-
...
-
{{JSxRef("AsyncIterator.prototype.filter()")}} 
-
...
-
{{JSxRef("AsyncIterator.prototype.take()")}} 
-
...
-
{{JSxRef("AsyncIterator.prototype.drop()")}} 
-
...
-
{{JSxRef("AsyncIterator.prototype.asIndexedPairs()")}} 
-
...
-
{{JSxRef("AsyncIterator.prototype.flatMap()")}} 
-
...
-
{{JSxRef("AsyncIterator.prototype.reduce()")}} 
-
...
-
{{JSxRef("AsyncIterator.prototype.toArray()")}} 
-
...
-
{{JSxRef("AsyncIterator.prototype.forEach()")}} 
-
...
-
{{JSxRef("AsyncIterator.prototype.some()")}} 
-
...
-
{{JSxRef("AsyncIterator.prototype.every()")}} 
-
...
-
{{JSxRef("AsyncIterator.prototype.find()")}} 
-
...
-
{{JSxRef("AsyncIterator.prototype.@@iterator()", "AsyncIterator.prototype[@@iterator]()")}}
-
返回该 AsyncIterator 实例。
-
- -

实现方法

- -
-
{{JSxRef("AsyncIterator.prototype.next()", "<implementation>.prototype.next()")}}
-
获取 AsyncIterator 中的下一项
-
{{JSxRef("AsyncIterator.prototype.return()", "<implementation>.prototype.next()")}}{{Optional_Inline}}
-
返回给出的值,并结束迭代。
-
{{JSxRef("AsyncIterator.prototype.throw()", "<implementation>.prototype.next()")}}{{Optional_Inline}}
-
抛出一个迭代器错误(同时也终止了迭代器,除非是在该迭代器内部被捕获)。
-
- -

规范

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
ESNext Iterator Helpers ProposalStage 2 DraftInitial definition
- -

浏览器兼容性

- - - -

{{Compat("javascript.builtins.AsyncIterator")}}

- -

另请参阅

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/boolean/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/boolean/prototype/index.html deleted file mode 100644 index cb7f351bd1..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/boolean/prototype/index.html +++ /dev/null @@ -1,76 +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)}}
- -

描述

- -

{{jsxref("Boolean")}}实例继承自Boolean.prototype。你可以使用构造函数的原型对象向所有{{jsxref("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/zh-cn/web/javascript/reference/global_objects/dataview/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/dataview/prototype/index.html deleted file mode 100644 index 3285efa3d3..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/dataview/prototype/index.html +++ /dev/null @@ -1,103 +0,0 @@ ---- -title: DataView.prototype -slug: Web/JavaScript/Reference/Global_Objects/DataView/prototype -tags: - - DataView属性 -translation_of: Web/JavaScript/Reference/Global_Objects/DataView -translation_of_original: Web/JavaScript/Reference/Global_Objects/DataView/prototype ---- -
{{JSRef}}
- -

DataView.prototype 表示{{jsxref("DataView")}}的原型

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

描述

- -

DataView 的实例从DataView.prototype继承。就像所有的构造器,你可以修改原型来改变生成的DataView实例。

- -

属性

- -
-
{{jsxref("DataView.prototype.constructor")}}
-
指定用来生成原型的构造函数.初始化值是标准内置DataView构造器.
-
{{jsxref("DataView.prototype.buffer")}} {{readonlyInline}}
-
被视图引入的{{jsxref("ArrayBuffer")}}.创建实例的时候已固化因此是只读的.
-
{{jsxref("DataView.prototype.byteLength")}} {{readonlyInline}}
-
从 {{jsxref("ArrayBuffer")}}中读取的字节长度. 创建实例的时候已固化因此是只读的.
-
{{jsxref("DataView.prototype.byteOffset")}} {{readonlyInline}}
-
从 {{jsxref("ArrayBuffer")}}读取时的偏移字节长度. 创建实例的时候已固化因此是只读的.
-
- -

方法

- -

- -
-
{{jsxref("DataView.prototype.getInt8()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处获取一个8-bit数(一个字节).
-
{{jsxref("DataView.prototype.getUint8()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处获取一个8-bit数(无符号字节).
-
{{jsxref("DataView.prototype.getInt16()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处获取一个16-bit数(短整型).
-
{{jsxref("DataView.prototype.getUint16()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处获取一个16-bit数(无符号短整型).
-
{{jsxref("DataView.prototype.getInt32()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处获取一个32-bit数(长整型).
-
{{jsxref("DataView.prototype.getUint32()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处获取一个32-bit数(无符号长整型).
-
{{jsxref("DataView.prototype.getFloat32()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处获取一个32-bit数(浮点型).
-
{{jsxref("DataView.prototype.getFloat64()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处获取一个64-bit数(双精度浮点型).
-
- -

- -
-
{{jsxref("DataView.prototype.setInt8()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处储存一个8-bit数(一个字节).
-
{{jsxref("DataView.prototype.setUint8()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处储存一个8-bit数(无符号字节).
-
{{jsxref("DataView.prototype.setInt16()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处储存一个16-bit数(短整型).
-
{{jsxref("DataView.prototype.setUint16()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处储存一个16-bit数(无符号短整型).
-
{{jsxref("DataView.prototype.setInt32()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处储存一个32-bit数(长整型).
-
{{jsxref("DataView.prototype.setUint32()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处储存一个32-bit数(无符号长整型).
-
{{jsxref("DataView.prototype.setFloat32()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处储存一个32-bit数(浮点型).
-
{{jsxref("DataView.prototype.setFloat64()")}}
-
{{jsxref("DataView")}}起始位置以byte为计数的指定偏移量(byteOffset)处储存一个64-bit数(双精度浮点型).
-
- -

规范

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-dataview.prototype', 'DataView.prototype')}}{{Spec2('ES6')}}Initial definition.
- -

浏览器支持

- - - -

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

- -

另见

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/date/prototype/index.html deleted file mode 100644 index da3d715018..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/date/prototype/index.html +++ /dev/null @@ -1,181 +0,0 @@ ---- -title: Date.prototype -slug: Web/JavaScript/Reference/Global_Objects/Date/prototype -tags: - - Date - - JavaScript - - Property -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)}}
- -

描述

- -

{{jsxref("Date")}}实例继承自Date.prototype。可以通过修改构造函数的原型对象来影响 {{jsxref("Date")}}实例继承的属性和方法。

- -

为了兼容千禧年计算(也即考虑到 2000 年),应该总是指定完整的年份,例如,使用 1998,而不是 98。为了方便以完整的格式指定年份, JavaScript 包含了相应的方法{{jsxref("Global_Objects/Date/getFullYear", "getFullYear()")}},{{jsxref("Global_Objects/Date/setFullYear", "setFullYear()")}}, {{jsxref("Global_Objects/Date/getUTCFullYear", "getUTCFullYear()")}} 和{{jsxref("Global_Objects/Date/setUTCFullYear", "setUTCFullYear()")}}。

- -

从 ECMAScript 6 开始,Date.prototype本身就是一个普通的对象。不是{{jsxref("Date")}}的实例。

- -

属性

- -
-
Date.prototype.constructor
-
返回创建该实例的函数。默认是Date构造函数。
-
- -

方法

- -

Getter

- -
-
{{jsxref("Date.prototype.getDate()")}}
-
根据本地时间返回指定日期对象的月份中的第几天(1-31)。
-
{{jsxref("Date.prototype.getDay()")}}
-
根据本地时间返回指定日期对象的星期中的第几天(0-6)。
-
{{jsxref("Date.prototype.getFullYear()")}}
-
根据本地时间返回指定日期对象的年份(四位数年份时返回四位数字)。
-
{{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 00:00:00 UTC(协调世界时)到该日期经过的毫秒数,对于1970-1-1 00:00:00 UTC之前的时间返回负值。
-
{{jsxref("Date.prototype.getTimezoneOffset()")}}
-
返回当前时区的时区偏移。
-
{{jsxref("Date.prototype.getUTCDate()")}}
-
根据世界时返回特定日期对象一个月的第几天(1-31).
-
{{jsxref("Date.prototype.getUTCDay()")}}
-
根据世界时返回特定日期对象一个星期的第几天(0-6).
-
{{jsxref("Date.prototype.getUTCFullYear()")}}
-
根据世界时返回特定日期对象所在的年份(4位数).
-
{{jsxref("Date.prototype.getUTCHours()")}}
-
根据世界时返回特定日期对象当前的小时(0-23).
-
{{jsxref("Date.prototype.getUTCMilliseconds()")}}
-
根据世界时返回特定日期对象的毫秒数(0-999).
-
{{jsxref("Date.prototype.getUTCMinutes()")}}
-
根据世界时返回特定日期对象的分钟数(0-59).
-
{{jsxref("Date.prototype.getUTCMonth()")}}
-
根据世界时返回特定日期对象的月份(0-11).
-
{{jsxref("Date.prototype.getUTCSeconds()")}}
-
根据世界时返回特定日期对象的秒数(0-59).
-
{{jsxref("Date.prototype.getYear()")}}{{deprecated_inline}}
-
根据特定日期返回年份 (通常 2-3 位数). 使用 {{jsxref("Global_Objects/Date/getFullYear", "getFullYear()")}} .
-
- -

Setter

- -
-
{{jsxref("Date.prototype.setDate()")}}
-
根据本地时间为指定的日期对象设置月份中的第几天。
-
{{jsxref("Date.prototype.setFullYear()")}}
-
根据本地时间为指定日期对象设置完整年份(四位数年份是四个数字)。
-
{{jsxref("Date.prototype.setHours()")}}
-
根据本地时间为指定日期对象设置小时数。
-
{{jsxref("Date.prototype.setMilliseconds()")}}
-
根据本地时间为指定日期对象设置毫秒数。
-
{{jsxref("Date.prototype.setMinutes()")}}
-
根据本地时间为指定日期对象设置分钟数。
-
{{jsxref("Date.prototype.setMonth()")}}
-
根据本地时间为指定日期对象设置月份。
-
{{jsxref("Date.prototype.setSeconds()")}}
-
根据本地时间为指定日期对象设置秒数。
-
{{jsxref("Date.prototype.setTime()")}}
-
通过指定从 1970-1-1 00:00:00 UTC 开始经过的毫秒数来设置日期对象的时间,对于早于 1970-1-1 00:00:00 UTC的时间可使用负值。
-
{{jsxref("Date.prototype.setUTCDate()")}}
-
根据世界时设置 Date 对象中月份的一天 (1 ~ 31)。
-
{{jsxref("Date.prototype.setUTCFullYear()")}}
-
根据世界时设置 Date 对象中的年份(四位数字)。
-
{{jsxref("Date.prototype.setUTCHours()")}}
-
根据世界时设置 Date 对象中的小时 (0 ~ 23)。
-
{{jsxref("Date.prototype.setUTCMilliseconds()")}}
-
根据世界时设置 Date 对象中的毫秒 (0 ~ 999)。
-
{{jsxref("Date.prototype.setUTCMinutes()")}}
-
根据世界时设置 Date 对象中的分钟 (0 ~ 59)。
-
{{jsxref("Date.prototype.setUTCMonth()")}}
-
根据世界时设置 Date 对象中的月份 (0 ~ 11)。
-
{{jsxref("Date.prototype.setUTCSeconds()")}}
-
根据世界时设置 Date 对象中的秒钟 (0 ~ 59)。
-
{{jsxref("Date.prototype.setYear()")}} {{deprecated_inline}}
-
setYear() 方法用于设置年份。请使用 {{jsxref("Global_Objects/Date/setFullYear", "setFullYear()")}} 方法代替。
-
- -

Conversion getter

- -
-
{{jsxref("Date.prototype.toDateString()")}}
-
以人类易读(human-readable)的形式返回该日期对象日期部分的字符串。
-
{{jsxref("Date.prototype.toISOString()")}}
-
把一个日期转换为符合 ISO 8601 扩展格式的字符串。
-
{{jsxref("Date.prototype.toJSON()")}}
-
使用 {{jsxref("Global_Objects/Date/toISOString", "toISOString()")}} 返回一个表示该日期的字符串。为了在 {{jsxref("JSON.stringify()")}} 方法中使用。
-
{{jsxref("Date.prototype.toGMTString()")}} {{deprecated_inline}}
-
返回一个基于 GMT (UT) 时区的字符串来表示该日期。请使用 {{jsxref("Global_Objects/Date/toUTCString", "toUTCString()")}} 方法代替。
-
{{jsxref("Date.prototype.toLocaleDateString()")}}
-
返回一个表示该日期对象日期部分的字符串,该字符串格式与系统设置的地区关联(locality sensitive)。
-
{{jsxref("Date.prototype.toLocaleFormat()")}} {{non-standard_inline}}
-
使用格式字符串将日期转换为字符串。
-
{{jsxref("Date.prototype.toLocaleString()")}}
-
返回一个表示该日期对象的字符串,该字符串与系统设置的地区关联(locality sensitive)。覆盖了 {{jsxref("Global_Objects/Object/toLocaleString", "Object.prototype.toLocaleString()")}} 方法。
-
{{jsxref("Date.prototype.toLocaleTimeString()")}}
-
返回一个表示该日期对象时间部分的字符串,该字符串格式与系统设置的地区关联(locality sensitive)。
-
{{jsxref("Date.prototype.toSource()")}}{{non-standard_inline}}
-
返回一个与{{jsxref("Date")}}等价的原始字符串对象,你可以使用这个值去生成一个新的对象。重写了 {{jsxref("Object.prototype.toSource()")}} 这个方法。
-
{{jsxref("Date.prototype.toString()")}}
-
返回一个表示该日期对象的字符串。覆盖了{{jsxref("Object.prototype.toString()")}} 方法。
-
{{jsxref("Date.prototype.toTimeString()")}}
-
以人类易读格式返回日期对象时间部分的字符串。
-
{{jsxref("Date.prototype.toUTCString()")}}
-
把一个日期对象转换为一个以UTC时区计时的字符串。
-
{{jsxref("Date.prototype.valueOf()")}}
-
返回一个日期对象的原始值。覆盖了 {{jsxref("Object.prototype.valueOf()")}} 方法。
-
- -

规范

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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/zh-cn/web/javascript/reference/global_objects/error/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/error/prototype/index.html deleted file mode 100644 index 420b5634de..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/error/prototype/index.html +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: Error.prototype -slug: Web/JavaScript/Reference/Global_Objects/Error/prototype -tags: - - Error - - JavaScript - - Property - - 参考 - - 属性 -translation_of: Web/JavaScript/Reference/Global_Objects/Error -translation_of_original: Web/JavaScript/Reference/Global_Objects/Error/prototype ---- -
-

{{JSRef}}

- -

Error.prototype 属性代表 {{jsxref("Error")}} 的构造器。

- -

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

-
- -

描述

- -

所有 {{jsxref("Global_Objects/Error", "Error")}} 与 {{jsxref("Global_Objects/Error", "非标准Error", "#Error_types", 1)}} 的实例都继承自 Error.prototype。同所有构造器函数一样,你可以在构造器的 prototype 上添加属性或者方法,使其在所有该构造器的实例上生效。

- -

属性

- -

标准属性

- -
-
Error.prototype.constructor
-
实例原型的构造函数。
-
{{jsxref("Error.prototype.message")}}
-
错误信息。
-
{{jsxref("Error.prototype.name")}}
-
错误名。
-
- -

厂商特定扩展属性

- -
{{non-standard_header}}
- -

Microsoft

- -
-
{{jsxref("Error.prototype.description")}}
-
错误描述,与 {{jsxref("Error.prototype.message", "message")}} 相似。
-
{{jsxref("Error.prototype.number")}}
-
错误码。
-
- -

Mozilla

- -
-
{{jsxref("Error.prototype.fileName")}}
-
产生该错误的文件名。
-
{{jsxref("Error.prototype.lineNumber")}}
-
产生该错误的行号。
-
{{jsxref("Error.prototype.columnNumber")}}
-
产生该错误的列号。
-
{{jsxref("Error.prototype.stack")}}
-
错误堆栈。
-
- -

方法

- -
-
{{jsxref("Error.prototype.toSource()")}} {{non-standard_inline}}
-
返回一个包含特定 {{jsxref("Error")}} 对象的源代码字符串,你可以用该值新建一个新的对象,重写自 {{jsxref("Object.prototype.toSource()")}} 方法。
-
{{jsxref("Error.prototype.toString()")}}
-
返回一个表示该对象的字符串,重写自 {{jsxref("Object.prototype.toString()")}} 方法。
-
- -

规范

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
规范版本状态注解
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.11.3.1', 'Error')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-error.prototype', 'Error')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-error.prototype', 'Error')}}{{Spec2('ESDraft')}} 
- -

浏览器兼容性

- -
{{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/zh-cn/web/javascript/reference/global_objects/evalerror/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/evalerror/prototype/index.html deleted file mode 100644 index b68caa1f3f..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/evalerror/prototype/index.html +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: EvalError.prototype -slug: Web/JavaScript/Reference/Global_Objects/EvalError/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/EvalError -translation_of_original: Web/JavaScript/Reference/Global_Objects/EvalError/prototype ---- -
{{JSRef}}
- -

EvalError.prototype 属性是 {{jsxref("EvalError")}} 原型构造函数.

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

Description

- -

{{jsxref("EvalError")}} 全部实例都继承自EvalError.prototype. 你可以通过prototype去添加方法和属性.

- -

Properties

- -
-
EvalError.prototype.constructor
-
指定创建实例原型的函数.
-
{{jsxref("Error.prototype.message", "EvalError.prototype.message")}}
-
错误信息. 从 ECMA-262 开始 {{jsxref("EvalError")}} 提供 message (继承自{{jsxref("Error.prototype.message")}})属性, 详见 SpiderMonkey.
-
{{jsxref("Error.prototype.name", "EvalError.prototype.name")}}
-
错误名称.继承自 {{jsxref("Error")}}.
-
{{jsxref("Error.prototype.fileName", "EvalError.prototype.fileName")}}
-
引发错误的文件路径. 继承自 {{jsxref("Error")}}.
-
{{jsxref("Error.prototype.lineNumber", "EvalError.prototype.lineNumber")}}
-
引发错误所在行.继承自 {{jsxref("Error")}}.
-
{{jsxref("Error.prototype.columnNumber", "EvalError.prototype.columnNumber")}}
-
引发错误所在的列. 继承自{{jsxref("Error")}}.
-
{{jsxref("Error.prototype.stack", "EvalError.prototype.stack")}}
-
堆栈.继承自 {{jsxref("Error")}}.
-
- -

Methods

- -

虽然 {{jsxref("EvalError")}} 自己的属性方法较少, 但是通过原型链继承了很多有用的方法.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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.
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.EvalError")}}

-
- -

See also

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/function/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/function/prototype/index.html deleted file mode 100644 index a745753511..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/function/prototype/index.html +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: Function.prototype -slug: Web/JavaScript/Reference/Global_Objects/Function/prototype -tags: - - JavaScript - - 函数 - - 原型 - - 原型属性 -translation_of: Web/JavaScript/Reference/Global_Objects/Function -translation_of_original: Web/JavaScript/Reference/Global_Objects/Function/prototype ---- -
{{JSRef}}
- -

Function.prototype 属性存储了 {{jsxref("Function")}} 的原型对象。

- -

描述

- -

{{jsxref("Function")}}对象继承自 Function.prototype 属性。因此,Function.prototype 不能被修改。

- -

属性

- -
-
{{jsxref("Function.arguments")}} {{deprecated_inline()}}
-
以数组形式获取传入函数的所有参数。此属性已被{{jsxref("Functions_and_function_scope/arguments", "arguments")}}替代。
-
{{jsxref("Function.arity")}} {{obsolete_inline() }}
-
用于指定的函数的参数的个数,但已被删除。使用{{jsxref("Function.length","length")}}属性代替。
-
{{jsxref("Function.caller")}} {{ Non-standard_inline() }}
-
获取调用函数的具体对象。
-
{{jsxref("Function.length")}}
-
获取函数的接收参数个数。
-
{{jsxref("Function.name")}} {{ Non-standard_inline() }}
-
获取函数的名称。
-
{{jsxref("Function.displayName")}} {{ Non-standard_inline() }}
-
获取函数的display name。
-
Function.prototype.constructor
-
声明函数的原型构造方法,详细请参考 {{jsxref("Object.constructor")}} 。
-
- -

方法

- -
-
{{jsxref("Function.prototype.apply()")}}
-
在一个对象的上下文中应用另一个对象的方法;参数能够以数组形式传入。
-
{{jsxref("Function.prototype.bind()")}}
-
bind()方法会创建一个新函数,称为绑定函数.当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this,传入 bind()方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数.
-
{{jsxref("Function.prototype.call()")}}
-
在一个对象的上下文中应用另一个对象的方法;参数能够以列表形式传入。
-
{{jsxref("Function.prototype.isGenerator()")}} {{ Non-standard_inline() }}
-
若函数对象为generator,返回true,反之返回 false
-
{{jsxref("Function.prototype.toSource()")}} {{ Non-standard_inline() }}
-
获取函数的实现源码的字符串。 覆盖了 {{jsxref("Object.prototype.toSource")}} 方法。
-
{{jsxref("Function.prototype.toString()")}}
-
获取函数的实现源码的字符串。覆盖了 {{jsxref("Object.prototype.toString")}} 方法。
-
- -

规范

- - - - - - - - - - - - - - - - - - - - - - - - -
规范状态说明
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.Implemented in JavaScript 1.1
{{SpecName('ES5.1', '#sec-15.3.5.2', 'Function.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-instances-prototype', 'Function.prototype')}}{{Spec2('ES6')}} 
- -

浏览器兼容性

- -

{{ 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/zh-cn/web/javascript/reference/global_objects/generatorfunction/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/generatorfunction/prototype/index.html deleted file mode 100644 index 0f7179b3f5..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/generatorfunction/prototype/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: GeneratorFunction.prototype -slug: Web/JavaScript/Reference/Global_Objects/GeneratorFunction/prototype -tags: - - ECMAScript 2015 - - GeneratorFunction - - Iterator - - JavaScript - - Property - - Prototype - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/GeneratorFunction -translation_of_original: Web/JavaScript/Reference/Global_Objects/GeneratorFunction/prototype ---- -
{{JSRef}}
- -

GeneratorFunction.prototype属性是{{jsxref("GeneratorFunction")}}的原型对象。

- -

描述

- -

{{jsxref("GeneratorFunction")}} 的实例对象都继承于 GeneratorFunction.prototype. GeneratorFunction.prototype 不能被修改。

- -

属性

- -
-
GeneratorFunction.constructor
-
初始值是 {{jsxref("GeneratorFunction")}}.
-
GeneratorFunction.prototype.prototype
-
值是 %GeneratorPrototype%.
-
- -

规范

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

浏览器兼容

- - - -

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

- -

相关链接

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html deleted file mode 100644 index f74e8f9cf5..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html +++ /dev/null @@ -1,120 +0,0 @@ ---- -title: Intl.DateTimeFormat.prototype -slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/prototype -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)}} 

- -

描述

- -

参见 {{jsxref("DateTimeFormat")}}来看Intl.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")}}
-
Getter; 返回一个{{jsxref("DateTimeFormat", "DateTimeFormat")}}对象的根据locale和格式化参数格式化日期的函数。
-
- -

方法

- -
-
{{jsxref("DateTimeFormat.formatToParts", "Intl.DateTimeFormat.prototype.formatToParts()")}}
-
Returns an {{jsxref("Array")}} of objects representing the date string in parts that can be used for custom locale-aware formatting.
-
{{jsxref("DateTimeFormat.resolvedOptions", "Intl.DateTimeFormat.prototype.resolvedOptions()")}}
-
返回一个新的属性对象,反射出在对象初始化过程中计算出的locale和options的各个值。
-
- -

规范

- - - - - - - - - - - - - - - - - - - - - - - - -
规范版本规范状态注解
{{SpecName('ES Int 1.0', '#sec-12.2.1', 'Intl.DateTimeFormat.prototype')}}{{Spec2('ES Int 1.0')}}初始定义
{{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')}} 
- -

浏览器兼容性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome("24")}}{{CompatGeckoDesktop("29")}}{{CompatIE("11")}}{{CompatOpera("15")}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome("26")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

参见

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/prototype/index.html deleted file mode 100644 index d98bdfac5a..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/map/prototype/index.html +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: Map.prototype -slug: Web/JavaScript/Reference/Global_Objects/Map/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Map -translation_of_original: Web/JavaScript/Reference/Global_Objects/Map/prototype ---- -
{{JSRef}}
- -

Map.prototype 属性表示 {{jsxref("Map")}}构造函数的原型对象。

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

描述

- -

{{jsxref("Map")}} 实例继承自{{jsxref("Map.prototype")}}。你可以使用这个构造函数的原型对象来给所有的Map实例添加属性或者方法。

- -

属性

- -
-
Map.prototype.constructor
-
返回一个函数,它创建了实例的原型。默认是{{jsxref("Map")}}函数。
-
{{jsxref("Map.prototype.size")}}
-
返回Map对象的键/值对的数量。
-
- -

方法

- -
-
{{jsxref("Map.prototype.clear()")}}
-
移除Map对象的所有键/值对 。
-
{{jsxref("Map.delete", "Map.prototype.delete(key)")}}
-
如果 Map 对象中存在该元素,则移除它并返回 true;否则如果该元素不存在则返回 false。随后调用 Map.prototype.has(key) 将返回 false
-
{{jsxref("Map.prototype.entries()")}}
-
返回一个新的 Iterator 对象,它按插入顺序包含了Map对象中每个元素的 [key, value] 数组
-
{{jsxref("Map.forEach", "Map.prototype.forEach(callbackFn[, thisArg])")}}
-
按插入顺序,为 Map对象里的每一键值对调用一次callbackFn函数。如果为forEach提供了thisArg,它将在每次回调中作为this值。
-
{{jsxref("Map.get", "Map.prototype.get(key)")}}
-
返回键对应的值,如果不存在,则返回undefined。
-
{{jsxref("Map.has", "Map.prototype.has(key)")}}
-
返回一个布尔值,表示Map实例是否包含键对应的值。
-
{{jsxref("Map.prototype.keys()")}}
-
返回一个新的 Iterator对象, 它按插入顺序包含了Map对象中每个元素的
-
{{jsxref("Map.set", "Map.prototype.set(key, value)")}}
-
设置Map对象中键的值。返回该Map对象。
-
{{jsxref("Map.prototype.values()")}}
-
返回一个新的Iterator对象,它按插入顺序包含了Map对象中每个元素的
-
{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}
-
返回一个新的Iterator对象,它按插入顺序包含了Map对象中每个元素的 [key, value] 数组
-
- -

规范

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

浏览器兼容性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support38{{ CompatGeckoDesktop("13") }}11257.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}38{{CompatGeckoMobile("13")}}{{CompatNo}}{{CompatNo}} -

8

-
-
- -

相关链接

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/acosh/index.html b/files/zh-cn/web/javascript/reference/global_objects/math/acosh/index.html new file mode 100644 index 0000000000..7869661836 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/math/acosh/index.html @@ -0,0 +1,91 @@ +--- +title: Math.acosh() +slug: Web/JavaScript/Reference/Global_Objects/Math/反双曲余弦值 +tags: + - JavaScript + - 双曲函数 + - 数学 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/acosh +--- +
{{JSRef}}
+ +

Math.acosh() 函数返回一个数的反双曲余弦值,即:

+ +

x1,Math.acosh(x)=arcosh(x)= the unique y0such thatcosh(y)=x\forall x \geq 1, \mathtt{\operatorname{Math.acosh}(x)} = \operatorname{arcosh}(x) = \text{ 唯一的} \; y \geq 0 \; \text{使得} \; \cosh(y) = x

+ +
{{EmbedInteractiveExample("pages/js/math-acosh.html")}}
+ + + +

语法

+ +
Math.acosh(x)
+ +

参数

+ +
+
x
+
一个数字。
+
+ +

返回值

+ +

返回给定数的反双曲余弦值,如果该数小于 1 则返回 {{jsxref("NaN")}}。

+ +

描述

+ +

因为 acosh() 是 Math 的静态方法,所以总应该直接调用 Math.acosh() ,而不是创建 Math 对象再调用该方法(Math 不是一个构造函数)。

+ +

示例

+ +

使用 Math.acosh()

+ +
Math.acosh(-1);  // NaN
+Math.acosh(0);   // NaN
+Math.acosh(0.5); // NaN
+Math.acosh(1);   // 0
+Math.acosh(2);   // 1.3169578969248166
+
+ +

当参数小于1时, Math.acosh()将返回 {{jsxref("NaN")}}。

+ +

向下兼容

+ +

x1x \geq 1 时,都有 arcosh(x)=ln(x+x2-1)\operatorname {arcosh} (x) = \ln \left(x + \sqrt{x^{2} - 1} \right) ,因此可以使用以下函数实现:

+ +
Math.acosh = Math.acosh || function(x) {
+  return Math.log(x + Math.sqrt(x * x - 1));
+};
+
+ +

规范

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-math.acosh', 'Math.acosh')}}
+ +

浏览器兼容性

+ + + +

{{Compat("javascript.builtins.Math.acosh")}}

+ +

参见

+ + diff --git "a/files/zh-cn/web/javascript/reference/global_objects/math/\345\217\215\345\217\214\346\233\262\344\275\231\345\274\246\345\200\274/index.html" "b/files/zh-cn/web/javascript/reference/global_objects/math/\345\217\215\345\217\214\346\233\262\344\275\231\345\274\246\345\200\274/index.html" deleted file mode 100644 index 7869661836..0000000000 --- "a/files/zh-cn/web/javascript/reference/global_objects/math/\345\217\215\345\217\214\346\233\262\344\275\231\345\274\246\345\200\274/index.html" +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: Math.acosh() -slug: Web/JavaScript/Reference/Global_Objects/Math/反双曲余弦值 -tags: - - JavaScript - - 双曲函数 - - 数学 - - 方法 -translation_of: Web/JavaScript/Reference/Global_Objects/Math/acosh ---- -
{{JSRef}}
- -

Math.acosh() 函数返回一个数的反双曲余弦值,即:

- -

x1,Math.acosh(x)=arcosh(x)= the unique y0such thatcosh(y)=x\forall x \geq 1, \mathtt{\operatorname{Math.acosh}(x)} = \operatorname{arcosh}(x) = \text{ 唯一的} \; y \geq 0 \; \text{使得} \; \cosh(y) = x

- -
{{EmbedInteractiveExample("pages/js/math-acosh.html")}}
- - - -

语法

- -
Math.acosh(x)
- -

参数

- -
-
x
-
一个数字。
-
- -

返回值

- -

返回给定数的反双曲余弦值,如果该数小于 1 则返回 {{jsxref("NaN")}}。

- -

描述

- -

因为 acosh() 是 Math 的静态方法,所以总应该直接调用 Math.acosh() ,而不是创建 Math 对象再调用该方法(Math 不是一个构造函数)。

- -

示例

- -

使用 Math.acosh()

- -
Math.acosh(-1);  // NaN
-Math.acosh(0);   // NaN
-Math.acosh(0.5); // NaN
-Math.acosh(1);   // 0
-Math.acosh(2);   // 1.3169578969248166
-
- -

当参数小于1时, Math.acosh()将返回 {{jsxref("NaN")}}。

- -

向下兼容

- -

x1x \geq 1 时,都有 arcosh(x)=ln(x+x2-1)\operatorname {arcosh} (x) = \ln \left(x + \sqrt{x^{2} - 1} \right) ,因此可以使用以下函数实现:

- -
Math.acosh = Math.acosh || function(x) {
-  return Math.log(x + Math.sqrt(x * x - 1));
-};
-
- -

规范

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-math.acosh', 'Math.acosh')}}
- -

浏览器兼容性

- - - -

{{Compat("javascript.builtins.Math.acosh")}}

- -

参见

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/number/prototype/index.html deleted file mode 100644 index 3abe34b74b..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/number/prototype/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: Number.prototype -slug: Web/JavaScript/Reference/Global_Objects/Number/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Number -translation_of_original: Web/JavaScript/Reference/Global_Objects/Number/prototype ---- -
- {{JSRef("Global_Objects", "Number")}}
-

概述

-

Number.prototype 属性表示 {{jsxref("Global_Objects/Number", "Number")}} 构造函数的原型。

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

描述

-

所有 Number 实例都继承自 Number.prototype。修改 {{jsxref("Global_Objects/Number", "Number")}} 构造函数的原型对象会影响到所有 Number 实例。.

-

属性

-
-
- constructor
-
- 返回创建该实例对象的构造函数。默认为 {{jsxref("Global_Objects/Number", "Number")}} 对象。
-
-
- {{ jsOverrides("Object", "properties", "constructor") }}
-

方法

-
-
- {{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() }}
-
- Returns an object literal representing the specified Number object; you can use this value to create a new object. Overrides the {{jsxref("Object.prototype.toSource()")}} method.
-
- {{jsxref("Number.prototype.toString()")}}
-
- 返回一个表示该数值对象的字符串。覆盖了 {{jsxref("Object.prototype.toString()")}} 方法。
-
- {{jsxref("Number.prototype.valueOf()")}}
-
- 返回该数值对象的原始值。覆盖了 {{jsxref("Object.prototype.valueOf()")}} 方法。
-
-
- {{ jsOverrides("Object", "methods", "toExponential", "toFixed", "toLocaleString", "toPrecision", "toSource", "toString", "valueOf") }}
-
-  
-

规范

- - - - - - - - - - - - - - - - - - - - - - - -
规范版本规范状态注解
ECMAScript 1st Edition. Implemented in JavaScript 1.1StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.7.4', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-the-number-prototype-object', 'Number')}}{{Spec2('ES6')}} 
-

浏览器兼容性

-

{{ 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/zh-cn/web/javascript/reference/global_objects/object/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/object/prototype/index.html deleted file mode 100644 index 4dd70200f0..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/object/prototype/index.html +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: Object.prototype -slug: Web/JavaScript/Reference/Global_Objects/Object/prototype -tags: - - JavaScript - - Object - - Property -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的属性(包括方法),尽管这些属性可能被遮蔽(亦称为覆盖)。但是有时候可能故意创建不具有典型原型链继承的对象,比如通过{{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__")}} {{non-standard_inline}}
-
当未定义的对象成员被调用作方法的时候,允许定义并执行的函数。
-
{{jsxref("Object.prototype.__count__")}} {{obsolete_inline}}
-
用于直接返回用户定义的对象中可数的属性的数量。已被废除。
-
{{jsxref("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.defineGetter", "__defineGetter__")}} 定义的方法函数 。
-
{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
返回使用 {{jsxref("Object.defineSetter", "__defineSetter__")}} 定义的方法函数。
-
{{jsxref("Object.prototype.hasOwnProperty()")}}
-
返回一个布尔值 ,表示某个对象是否含有指定的属性,而且此属性非原型链继承的。
-
{{jsxref("Object.prototype.isPrototypeOf()")}}
-
返回一个布尔值,表示指定的对象是否在本对象的原型链中。
-
{{jsxref("Object.prototype.propertyIsEnumerable()")}}
-
判断指定属性是否可枚举,内部属性设置参见 ECMAScript [[Enumerable]] attribute
-
{{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 method(方法)的行为时,考虑在现有逻辑之前或之后通过封装你的扩展来注入代码。例如,此(未测试的)代码将在内置逻辑或其他人的扩展执行之前 pre-conditionally(预条件地)执行自定义逻辑。

- -

当一个函数被调用时,调用的参数被保留在类似数组 "变量" 的参数中。例如, 在调用 "myFn (a、b、c)"时, 在myFn 的主体内的参数将包含 3个类似数组的元素对应于 (a、b、c)。 使用钩子修改原型时,只需通过调用该函数的 apply (),将 this 与参数 (调用状态) 传递给当前行为。这种模式可以用于任何原型,如 Node.prototype、 Function.prototype 等.

- -
var current = Object.prototype.valueOf;
-
-// 由于我的属性 "-prop-value"是交叉性的, 并不总是
-// 在同一个原型链上,我想要修改 Object.prototype:
-Object.prototype.valueOf = function() {
-  if (this.hasOwnProperty('-prop-value')) {
-    return this['-prop-value'];
-  } else {
-    // 它看起来不像我的对象之一,因此,让我们退回到
-    // 默认行为,通过尽可能地复制当前行为来实现.
-    // 此apply的行为类似于其他语言中的"super".
-    // 即使 valueOf() 不带参数, 其他的钩子可能会带有.
-    return current.apply(this, arguments);
-  }
-}
- -

由于 JavaScript 并不完全具有子类对象, 所以原型是一种有用的变通方法, 可以使用某些函数的 "基类" 对象来充当对象。例如:

- -
var Person = function(name) {
-  this.name = name;
-  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, name);
-  this.title = title;
-};
-
-Employee.prototype = Object.create(Person.prototype);
-
-Employee.prototype.greet = function() {
-  if (this.canTalk) {
-    console.log('Hi, I am ' + this.name + ', the ' + this.title);
-  }
-};
-
-var Customer = function(name) {
-  Person.call(this, name);
-};
-
-Customer.prototype = Object.create(Person.prototype);
-
-var Mime = function(name) {
-  Person.call(this, name);
-  this.canTalk = false;
-};
-
-Mime.prototype = Object.create(Person.prototype);
-
-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();
-
- -

规范

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in 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")}}

- -

相关链接

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/promise/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/promise/prototype/index.html deleted file mode 100644 index c9c7dc3f6a..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/promise/prototype/index.html +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: Promise.prototype -slug: Web/JavaScript/Reference/Global_Objects/Promise/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Promise -translation_of_original: Web/JavaScript/Reference/Global_Objects/Promise/prototype ---- -
{{JSRef("Global_Objects", "Promise")}}
- -

总结

- -

Promise.prototype 属性表示 {{jsxref("Promise")}} 构造器的原型.

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

描述

- -

{{jsxref("Promise")}} 实例继承自 {{jsxref("Promise.prototype")}}. 你可以在构造器的原型对象添加属性或方法到所有 Promise 实例上.

- -

属性

- -
-
Promise.prototype.constructor
-
返回被创建的实例函数.  默认为 {{jsxref("Promise")}} 函数.
-
- -

方法

- -
-
{{jsxref("Promise.catch", "Promise.prototype.catch(onRejected)")}}
-
添加一个拒绝(rejection) 回调到当前 promise, 返回一个新的promise。当这个回调函数被调用,新 promise 将以它的返回值来resolve,否则如果当前promise 进入fulfilled状态,则以当前promise的完成结果作为新promise的完成结果.
-
{{jsxref("Promise.then", "Promise.prototype.then(onFulfilled, onRejected)")}}
-
添加解决(fulfillment)和拒绝(rejection)回调到当前 promise, 返回一个新的 promise, 将以回调的返回值来resolve.
-
{{jsxref("Promise.finally", "Promise.prototype.finally(onFinally)")}}
-
添加一个事件处理回调于当前promise对象,并且在原promise对象解析完毕后,返回一个新的promise对象。回调会在当前promise运行完毕后被调用,无论当前promise的状态是完成(fulfilled)还是失败(rejected)
-
- -

规范

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-promise.prototype', 'Promise.prototype')}}{{Spec2('ES6')}}Initial definition.
- -

浏览器兼容

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support32{{CompatGeckoDesktop(24.0)}} as Future
- {{CompatGeckoDesktop(25.0)}} as Promise behind a flag[1]
- {{CompatGeckoDesktop(29.0)}} by default
{{CompatNo}}197.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatGeckoMobile(24.0)}} as Future
- {{CompatGeckoMobile(25.0)}} as Promise behind a flag[1]
- {{CompatGeckoMobile(29.0)}} by default
{{CompatNo}}{{CompatNo}}iOS 832
-
- -

[1] Gecko 24 has an experimental implementation of Promise, under the initial name of Future. It got renamed to its final name in Gecko 25, but disabled by default behind the flag dom.promise.enabled. Bug 918806 enabled Promises by default in Gecko 29.

- -

另见

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/apply/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/apply/index.html deleted file mode 100644 index 62b8b67f5f..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/apply/index.html +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: handler.apply() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply -tags: - - ECMAScript6 - - JavaScript - - Method - - Proxy -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply ---- -
{{JSRef}}
- -

handler.apply() 方法用于拦截函数的调用。

- -
{{EmbedInteractiveExample("pages/js/proxyhandler-apply.html", "taller")}}
- - - -

语法

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

参数

- -

以下是传递给apply方法的参数,this上下文绑定在handler对象上.

- -
-
target
-
目标对象(函数)。
-
thisArg
-
被调用时的上下文对象。
-
argumentsList
-
被调用时的参数数组。
-
- -

返回值

- -

apply方法可以返回任何值。

- -

描述

- -

handler.apply 方法用于拦截函数的调用。

- -

拦截

- -

该方法会拦截目标对象的以下操作:

- - - -

约束

- -

如果违反了以下约束,代理将抛出一个TypeError:

- -

target必须是可被调用的。也就是说,它必须是一个函数对象。

- -

示例

- -

以下代码演示如何捕获函数的调用。

- -
var p = new Proxy(function() {}, {
-  apply: function(target, thisArg, argumentsList) {
-    console.log('called: ' + argumentsList.join(', '));
-    return argumentsList[0] + argumentsList[1] + argumentsList[2];
-  }
-});
-
-console.log(p(1, 2, 3)); // "called: 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')}} 
- -

浏览器兼容性

- -
- - -

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

-
- -

另见

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/construct/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/construct/index.html deleted file mode 100644 index 209e9752e3..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/construct/index.html +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: handler.construct() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/construct -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/construct ---- -
{{JSRef}}
- -

handler.construct() 方法用于拦截{{jsxref("Operators/new", "new")}} 操作符. 为了使new操作符在生成的Proxy对象上生效,用于初始化代理的目标对象自身必须具有[[Construct]]内部方法(即 new target 必须是有效的)。

- -

{{EmbedInteractiveExample("pages/js/proxyhandler-construct.html", "taller")}}

- -

语法

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

参数

- -

下面的参数将会传递给construct方法,this绑定在handler上。

- -
-
target
-
目标对象。
-
argumentsList
-
constructor的参数列表。
-
newTarget
-
最初被调用的构造函数,就上面的例子而言是p。
-
- -

返回值

- -

construct 方法必须返回一个对象。

- -

描述

- -

handler.construct() 方法用于拦截 {{jsxref("Operators/new", "new")}}操作符。

- -

拦截

- -

该拦截器可以拦截以下操作:

- - - -

约束

- -

如果违反以下约定,代理将会抛出错误 {{jsxref("TypeError")}}:

- - - -

示例

- -

下面代码演示如何拦截 {{jsxref("Operators/new", "new")}} 操作。

- -
var p = new Proxy(function() {}, {
-  construct: function(target, argumentsList, newTarget) {
-    console.log('called: ' + argumentsList.join(', '));
-    return { value: argumentsList[0] * 10 };
-  }
-});
-
-console.log(new p(1).value); // "called: 1"
-                             // 10
-
- -

下面的代码违反了约定.

- -
var p = new Proxy(function() {}, {
-  construct: function(target, argumentsList, newTarget) {
-    return 1;
-  }
-});
-
-new p(); // TypeError is thrown
-
- -

下面的代码未能正确的初始化Proxy。Proxy初始化时,传给它的target 必须具有一个有效的constructor供new操作符调用。

- -
var p = new Proxy({}, {
-  construct: function(target, argumentsList, newTarget) {
-    return {};
-  }
-});
-
-new p(); // TypeError is thrown, "p" is not a constructor
-
- -

规范

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

浏览器兼容性

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

相关主题

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/defineproperty/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/defineproperty/index.html deleted file mode 100644 index 9912e043a0..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/defineproperty/index.html +++ /dev/null @@ -1,181 +0,0 @@ ---- -title: handler.defineProperty() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/defineProperty -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/defineProperty ---- -
{{JSRef}}
- -

handler.defineProperty() 用于拦截对对象的 {{jsxref("Object.defineProperty()")}} 操作。

- -

语法

- -
var p = new Proxy(target, {
-  defineProperty: function(target, property, descriptor) {
-  }
-});
-
- -

参数

- -

下列参数将会被传递给 defineProperty 方法。 this 绑定在 handler 对象上。

- -
-
target
-
目标对象。
-
property
-
待检索其描述的属性名。
-
descriptor
-
待定义或修改的属性的描述符。
-
- -

返回值

- -

defineProperty 方法必须以一个 {{jsxref("Boolean")}} 返回,表示定义该属性的操作成功与否。

- -

描述

- -

handler.defineProperty() 用于拦截对对象的 {{jsxref("Object.defineProperty()")}} 操作。

- -

拦截

- -

该方法会拦截目标对象的以下操作 :

- - - -

不变量

- -

如果违背了以下的不变量,proxy会抛出 {{jsxref("TypeError")}}:

- - - -

示例

- -

以下代码演示如何拦截对目标对象的 {{jsxref("Object.defineProperty()")}} 操作。

- -
var p = new Proxy({}, {
-  defineProperty: function(target, prop, descriptor) {
-    console.log('called: ' + prop);
-    return true;
-  }
-});
-
-var desc = { configurable: true, enumerable: true, value: 10 };
-Object.defineProperty(p, 'a', desc); // "called: a"
-
- -

当调用 {{jsxref("Object.defineProperty()")}} 或者 {{jsxref("Reflect.defineProperty()")}},传递给 definePropertydescriptor   有一个限制 - 只有以下属性才有用,非标准的属性将会被无视 :

- - - -
var p = new Proxy({}, {
-  defineProperty(target, prop, descriptor) {
-    console.log(descriptor);
-    return Reflect.defineProperty(target, prop, descriptor);
-  }
-});
-
-Object.defineProperty(p, 'name', {
-  value: 'proxy',
-  type: 'custom'
-});  // { value: 'proxy' }
-
- -

规范

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc', '[[DefineOwnProperty]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc', '[[DefineOwnProperty]]')}}{{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/zh-cn/web/javascript/reference/global_objects/proxy/handler/deleteproperty/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/deleteproperty/index.html deleted file mode 100644 index 6cb4255755..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/deleteproperty/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: handler.deleteProperty() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/deleteProperty -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/deleteProperty ---- -
{{JSRef}}
- -

handler.deleteProperty() 方法用于拦截对对象属性的 {{jsxref("Operators/delete", "delete")}} 操作。

- -

语法

- -
var p = new Proxy(target, {
-  deleteProperty: function(target, property) {
-  }
-});
-
- -

参数

- -

deleteProperty 方法将会接受以下参数。 this 被绑定在 handler上。

- -
-
target
-
目标对象。
-
property
-
待删除的属性名。
-
- -

返回值

- -

deleteProperty 必须返回一个 {{jsxref("Boolean")}} 类型的值,表示了该属性是否被成功删除。

- -

描述

- -

handler.deleteProperty() 方法可以拦截 {{jsxref("Operators/delete", "delete")}} 操作。

- -

拦截

- -

该方法会拦截以下操作:

- - - -

不变量

- -

如果违背了以下不变量,proxy 将会抛出一个 {{jsxref("TypeError")}}:

- - - -

示例

- -

以下代码演示了对 {{jsxref("Operators/delete", "delete")}} 操作的拦截。

- -
var p = new Proxy({}, {
-  deleteProperty: function(target, prop) {
-    console.log('called: ' + prop);
-    return true;
-  }
-});
-
-delete p.a; // "called: a"
-
- -

规范

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-delete-p', '[[Delete]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-delete-p', '[[Delete]]')}}{{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/zh-cn/web/javascript/reference/global_objects/proxy/handler/get/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/get/index.html deleted file mode 100644 index 14a350436a..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/get/index.html +++ /dev/null @@ -1,177 +0,0 @@ ---- -title: handler.get() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/get -tags: - - ECMAScript6 - - JavaScript - - Method - - Proxy -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/get ---- -
{{JSRef}}
- -

handler.get() 方法用于拦截对象的读取属性操作。

- -

语法

- -
var p = new Proxy(target, {
-  get: function(target, property, receiver) {
-  }
-});
-
- -

参数

- -

以下是传递给get方法的参数,this上下文绑定在handler对象上.

- -
-
target
-
目标对象。
-
property
-
被获取的属性名。
-
receiver
-
Proxy或者继承Proxy的对象
-
- -

返回值

- -

get方法可以返回任何值。

- -

描述

- -

handler.get 方法用于拦截对象的读取属性操作。

- -

拦截

- -

该方法会拦截目标对象的以下操作:

- - - -

约束

- -

如果违背了以下的约束,proxy会抛出 {{jsxref("TypeError")}}:

- - - -

示例

- -

以下代码演示如何拦截属性值的读取操作。

- -
var p = new Proxy({}, {
-  get: function(target, prop, receiver) {
-    console.log("called: " + prop);
-    return 10;
-  }
-});
-
-console.log(p.a); // "called: a"
-                  // 10
-
- -

以下代码演示违反约束的情况。

- -
var obj = {};
-Object.defineProperty(obj, "a", {
-  configurable: false,
-  enumerable: false,
-  value: 10,
-  writable: false
-});
-
-var p = new Proxy(obj, {
-  get: function(target, prop) {
-    return 20;
-  }
-});
-
-p.a; //会抛出TypeError
-
- -

规范

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver', '[[Get]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver', '[[Get]]')}}{{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/zh-cn/web/javascript/reference/global_objects/proxy/handler/getownpropertydescriptor/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/getownpropertydescriptor/index.html deleted file mode 100644 index 470b2c6ad9..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/getownpropertydescriptor/index.html +++ /dev/null @@ -1,168 +0,0 @@ ---- -title: handler.getOwnPropertyDescriptor() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/getOwnPropertyDescriptor -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/getOwnPropertyDescriptor ---- -
{{JSRef}}
- -

handler.getOwnPropertyDescriptor() 方法是 {{jsxref("Object.getOwnPropertyDescriptor()")}}  的钩子。

- -

语法

- -
var p = new Proxy(target, {
-  getOwnPropertyDescriptor: function(target, prop) {
-  }
-});
-
- -

参数

- -

下列参数会被传入 getOwnPropertyDescriptor 方法中。这是绑定到handler上。 

- -
-
target
-
目标对象。
-
prop
-
返回属性名称的描述。
-
- -

返回值

- -

getOwnPropertyDescriptor 方法必须返回一个 object 或 undefined

- -

描述

- -

handler.getOwnPropertyDescriptor() 方法是 {{jsxref("Object.getOwnPropertyDescriptor()")}} 的陷阱。

- -

拦截

- -

这个陷阱可以拦截这些操作:

- - - -

不变量

- -

如果下列不变量被违反,代理将抛出一个 {{jsxref("TypeError")}}:

- - - -

示例

- -

以下是 {{jsxref("Object.getOwnPropertyDescriptor()")}} 的代码陷阱:

- -
var p = new Proxy({ a: 20}, {
-  getOwnPropertyDescriptor: function(target, prop) {
-    console.log('called: ' + prop);
-    return { configurable: true, enumerable: true, value: 10 };
-  }
-});
-
-console.log(Object.getOwnPropertyDescriptor(p, 'a').value); // "called: a"
-                                                            // 10
-
- -

以下代码则违反了不变量。

- -
var obj = { a: 10 };
-Object.preventExtensions(obj);
-var p = new Proxy(obj, {
-  getOwnPropertyDescriptor: function(target, prop) {
-    return undefined;
-  }
-});
-
-Object.getOwnPropertyDescriptor(p, 'a'); // TypeError is thrown
-
- -

规范

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p', '[[GetOwnProperty]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p', '[[GetOwnProperty]]')}}{{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/zh-cn/web/javascript/reference/global_objects/proxy/handler/getprototypeof/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/getprototypeof/index.html deleted file mode 100644 index 215d2d9646..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/getprototypeof/index.html +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: handler.getPrototypeOf() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/getPrototypeOf -tags: - - ECMAScript 2015 - - JavaScript - - Method - - Proxy - - 方法 -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/getPrototypeOf ---- -
{{JSRef("Global_Objects", "Proxy")}}
- -

handler.getPrototypeOf() 是一个代理(Proxy)方法,当读取代理对象的原型时,该方法就会被调用。

- -
{{EmbedInteractiveExample("pages/js/proxyhandler-getprototypeof.html", "taller")}}
- - - -

语法

- -
const p = new Proxy(obj, {
-  getPrototypeOf(target) {
-  ...
-  }
-});
-
- -

参数

- -

getPrototypeOf 方法被调用时,this 指向的是它所属的处理器对象。

- -
-
target
-
被代理的目标对象。
-
- -

返回值

- -

getPrototypeOf 方法的返回值必须是一个对象或者 null

- -

描述

- -

在 JavaScript 中,下面这五种操作(方法/属性/运算符)可以触发 JS 引擎读取一个对象的原型,也就是可以触发 getPrototypeOf() 代理方法的运行:

- - - -

如果遇到了下面两种情况,JS 引擎会抛出 {{jsxref("TypeError")}} 异常:

- - - -

示例

- -

基本用法

- -
var obj = {};
-var proto = {};
-var handler = {
-    getPrototypeOf(target) {
-        console.log(target === obj);   // true
-        console.log(this === handler); // true
-        return proto;
-    }
-};
-
-var p = new Proxy(obj, handler);
-console.log(Object.getPrototypeOf(p) === proto);    // true
-
- -

5 种触发 getPrototypeOf 代理方法的方式

- -
var obj = {};
-var p = new Proxy(obj, {
-    getPrototypeOf(target) {
-        return Array.prototype;
-    }
-});
-console.log(
-    Object.getPrototypeOf(p) === Array.prototype,  // true
-    Reflect.getPrototypeOf(p) === Array.prototype, // true
-    p.__proto__ === Array.prototype,               // true
-    Array.prototype.isPrototypeOf(p),              // true
-    p instanceof Array                             // true
-);
-
- -

两种情况下的异常

- -
var obj = {};
-var p = new Proxy(obj, {
-    getPrototypeOf(target) {
-        return "foo";
-    }
-});
-Object.getPrototypeOf(p); // TypeError: "foo" is not an object or null
-
-var obj = Object.preventExtensions({});
-var p = new Proxy(obj, {
-    getPrototypeOf(target) {
-        return {};
-    }
-});
-Object.getPrototypeOf(p); // TypeError: expected same prototype value
-
- -

规范

- - - - - - - - - - -
规范
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof', '[[GetPrototypeOf]]')}}
- -

浏览器兼容性

- - - -

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

- -

参见

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/has/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/has/index.html deleted file mode 100644 index fead0846ff..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/has/index.html +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: handler.has() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/has -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/has ---- -
{{JSRef}}
- -

 handler.has() 方法是针对 {{jsxref("Operators/in", "in")}} 操作符的代理方法。

- - - - - -

{{EmbedInteractiveExample("pages/js/proxyhandler-has.html", "taller")}}

- - - - - -

语法

- -
var p = new Proxy(target, {
-  has: function(target, prop) {
-  }
-});
-
- -

参数

- -

下面是传递给 has 方法的参数. this is bound to the handler.

- -
-
target
-
目标对象.
-
prop
-
需要检查是否存在的属性.
-
- -

返回值

- -

has 方法返回一个 boolean 属性的值.

- -

描述

- -

handler.has 方法可以看作是针对 {{jsxref("Operators/in", "in")}} 操作的钩子.

- -

拦截

- -

这个钩子可以拦截下面这些操作:

- - - -

约束

- -

如果违反了下面这些规则,  proxy 将会抛出 {{jsxref("TypeError")}}:

- - - -

示例

- -

下面的代码拦截了 {{jsxref("Operators/in", "in")}} 操作符.

- -
var p = new Proxy({}, {
-  has: function(target, prop) {
-    console.log('called: ' + prop);
-    return true;
-  }
-});
-
-console.log('a' in p); // "called: a"
-                       // true
-
- -

下面的代码违反了约束.

- -
var obj = { a: 10 };
-Object.preventExtensions(obj);
-var p = new Proxy(obj, {
-  has: function(target, prop) {
-    return false;
-  }
-});
-
-'a' in p; // TypeError is thrown
-
- -

规范

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-hasproperty-p', '[[HasProperty]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-hasproperty-p', '[[HasProperty]]')}}{{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/zh-cn/web/javascript/reference/global_objects/proxy/handler/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/index.html deleted file mode 100644 index 26d1ad3517..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/index.html +++ /dev/null @@ -1,77 +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}}
- -
Proxy 的 handler 对象是一个占位符对象,它包含了用于 {{jsxref("Proxy")}} 的陷阱(Trap)函数。
- -
此处可以理解为由Proxy所暴露出的钩子函数,handler作为挂载钩子函数的对象存在,不同的操作会触发不同的钩子函数
- -
,handler提供了覆写钩子函数的方法。
- -

方法

- -

所有的陷阱是可选的。如果某个陷阱没有定义,那么就会保留默认行为。

- -
-
{{jsxref("Global_Objects/Proxy/handler/getPrototypeOf", "handler.getPrototypeOf()")}}
-
在读取代理对象的原型时触发该操作,比如在执行 {{jsxref("Object.getPrototypeOf")}}(proxy) 时。
-
{{jsxref("Global_Objects/Proxy/handler/setPrototypeOf", "handler.setPrototypeOf()")}}
-
在设置代理对象的原型时触发该操作,比如在执行 {{jsxref("Object.setPrototypeOf")}}(proxy, null) 时。
-
{{jsxref("Global_Objects/Proxy/handler/isExtensible", "handler.isExtensible()")}}
-
在判断一个代理对象是否是可扩展时触发该操作,比如在执行 {{jsxref("Object.isExtensible")}}(proxy) 时。
-
{{jsxref("Global_Objects/Proxy/handler/preventExtensions", "handler.preventExtensions()")}}
-
在让一个代理对象不可扩展时触发该操作,比如在执行 {{jsxref("Object.preventExtensions")}}(proxy) 时。
-
{{jsxref("Global_Objects/Proxy/handler/getOwnPropertyDescriptor", "handler.getOwnPropertyDescriptor()")}}
-
在获取代理对象某个属性的属性描述时触发该操作,比如在执行 {{jsxref("Object.getOwnPropertyDescriptor")}}(proxy, "foo") 时。
-
{{jsxref("Global_Objects/Proxy/handler/defineProperty", "handler.defineProperty()")}}
-
在定义代理对象某个属性时的属性描述时触发该操作,比如在执行 {{jsxref("Object.defineProperty")}}(proxy, "foo", {}) 时。
-
{{jsxref("Global_Objects/Proxy/handler/has", "handler.has()")}}
-
在判断代理对象是否拥有某个属性时触发该操作,比如在执行 "foo" {{jsxref("Operators/in", "in")}} proxy 时。
-
{{jsxref("Global_Objects/Proxy/handler/get", "handler.get()")}}
-
在读取代理对象的某个属性时触发该操作,比如在执行 proxy.foo 时。
-
{{jsxref("Global_Objects/Proxy/handler/set", "handler.set()")}}
-
在给代理对象的某个属性赋值时触发该操作,比如在执行 proxy.foo = 1 时。
-
{{jsxref("Global_Objects/Proxy/handler/deleteProperty", "handler.deleteProperty()")}}
-
在删除代理对象的某个属性时触发该操作,即使用 {{jsxref("Operators/delete", "delete")}} 运算符,比如在执行 delete proxy.foo 时。
-
{{jsxref("Global_Objects/Proxy/handler/ownKeys", "handler.ownKeys()")}}
-
{{jsxref("Object.getOwnPropertyNames")}} 和{{jsxref("Object.getOwnPropertySymbols")}} 的陷阱。
-
{{jsxref("Global_Objects/Proxy/handler/apply", "handler.apply()")}}
-
函数调用操作的陷阱。
-
{{jsxref("Global_Objects/Proxy/handler/construct", "handler.construct()")}}
-
{{jsxref("Operators/new", "new")}} 运算符的陷阱。
-
- -

一些不标准的陷阱已经废弃并且被移除了

- -

规范

- - - - - - - - - - -
规范
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}
- -

浏览器兼容性

- - - -

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

- -

相关链接

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/isextensible/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/isextensible/index.html deleted file mode 100644 index 7be418197f..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/isextensible/index.html +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: handler.isExtensible() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/isExtensible -tags: - - ECMAScript 2015 - - JavaScript - - Method - - Proxy -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/isExtensible ---- -
{{JSRef}}
-handler.isExtensible() 方法用于拦截对对象的Object.isExtensible()。
- -
-

{{EmbedInteractiveExample("pages/js/proxyhandler-isextensible.html", "taller")}}

-
- -

语法

- -
var p = new Proxy(target, {
-  isExtensible: function(target) {
-  }
-});
-
- -

参数

- -

下列参数将会被传递给 isExtensible方法。 this 绑定在 handler 对象上。

- -
-
target
-
目标对象。
-
- -

返回值

- -

isExtensible方法必须返回一个 Boolean值或可转换成Boolean的值。

- -

描述

- -

handler.isExtensible()用于拦截对对象的Object.isExtensible()。

- -

拦截

- -

该方法会拦截目标对象的以下操作:

- - - -

约束

- -

如果违背了以下的约束,proxy会抛出 TypeError:

- - - -

示例

- -

以下代码演示{{jsxref("Object.isExtensible()")}}.

- -
var p = new Proxy({}, {
-  isExtensible: function(target) {
-    console.log('called');
-    return true;//也可以return 1;等表示为true的值
-  }
-});
-
-console.log(Object.isExtensible(p)); // "called"
-                                     // true
-
- -

以下代码演示违反约束的情况。

- -
var p = new Proxy({}, {
-  isExtensible: function(target) {
-    return false;//return 0;return NaN等都会报错
-  }
-});
-
-Object.isExtensible(p); // TypeError is thrown
-
- -

规范

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

浏览器兼容性

- -
- - -

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

-
- -

另见

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/ownkeys/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/ownkeys/index.html deleted file mode 100644 index 956b908375..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/ownkeys/index.html +++ /dev/null @@ -1,193 +0,0 @@ ---- -title: handler.ownKeys() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/ownKeys -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/ownKeys ---- -
{{JSRef}}
- -

handler.ownKeys() 方法用于拦截 {{jsxref("Reflect.ownKeys()")}}.

- - - -

{{EmbedInteractiveExample("pages/js/proxyhandler-ownkeys.html", "taller")}}

- - - -

语法

- -
var p = new Proxy(target, {
-  ownKeys: function(target) {
-  }
-});
-
- -

参数

- -

下面的参数被传递给ownKeys。this被绑定在handler上。

- -
-
target
-
目标对象.
-
- -

返回值

- -

ownKeys 方法必须返回一个可枚举对象.

- -

描述

- -

handler.ownKeys() 方法用于拦截 {{jsxref("Reflect.ownKeys()")}}.

- -

拦截

- -

该拦截器可以拦截以下操作::

- - - -

约束

- -

如果违反了下面的约束,proxy将抛出错误 {{jsxref("TypeError")}}:

- - - -

示例

- -

下面的代码拦截 {{jsxref("Object.getOwnPropertyNames()")}}.

- -
var p = new Proxy({}, {
-  ownKeys: function(target) {
-    console.log('called');
-    return ['a', 'b', 'c'];
-  }
-});
-
-console.log(Object.getOwnPropertyNames(p)); // "called"
-                                            // [ 'a', 'b', 'c' ]
- -

下面的代码违反了约定

- -
var obj = {};
-Object.defineProperty(obj, 'a', {
-  configurable: false,
-  enumerable: true,
-  value: 10 }
-);
-
-var p = new Proxy(obj, {
-  ownKeys: function(target) {
-    return [123, 12.5, true, false, undefined, null, {}, []];
-  }
-});
-
-console.log(Object.getOwnPropertyNames(p));
-
-// TypeError: proxy [[OwnPropertyKeys]] 必须返回一个数组
-// 数组元素类型只能是String或Symbol
-
- -

标准

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys', '[[OwnPropertyKeys]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys', '[[OwnPropertyKeys]]')}}{{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}}
-
- -

兼容性注意事项

- -

Firefox火狐

- - - -

另见

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/preventextensions/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/preventextensions/index.html deleted file mode 100644 index dd6823c9dd..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/preventextensions/index.html +++ /dev/null @@ -1,120 +0,0 @@ ---- -title: handler.preventExtensions() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/preventExtensions -tags: - - Proxy 代理 拦截 -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/preventExtensions ---- -
{{JSRef}}
- -

handler.preventExtensions() 方法用于设置对{{jsxref("Object.preventExtensions()")}}的拦截

- -

{{EmbedInteractiveExample("pages/js/proxyhandler-preventextensions.html", "taller")}}

- -

语法

- -
var p = new Proxy(target, {
-  preventExtensions: function(target) {
-  }
-});
-
- -

参数

- -

以下参数传递给 preventExtensions 方法. 它会绑定到这个handler.

- -
-
target
-
所要拦截的目标对象.
-
- -

返回值

- -

preventExtensions 方法返回一个布尔值.

- -

描述

- -

handler.preventExtensions() 拦截 {{jsxref("Object.preventExtensions()")}}返回一个布尔值.

- -

拦截

- -

这个trap可以拦截这些操作:

- - - -

约束

- -

如果违反了下列规则, proxy则会抛出一个 {{jsxref("TypeError")}}:

- - - -

示例

- -

以下代码演示了如何拦截{{jsxref("Object.preventExtensions()")}}。

- -
var p = new Proxy({}, {
-  preventExtensions: function(target) {
-    console.log('called');
-    Object.preventExtensions(target);
-    return true;
-  }
-});
-
-console.log(Object.preventExtensions(p)); // "called"
-                                          // false
-
- -

以下代码违反了约束.

- -
var p = new Proxy({}, {
-  preventExtensions: function(target) {
-    return true;
-  }
-});
-
-Object.preventExtensions(p); // 抛出类型错误
-
- -

规范

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

浏览器兼容性

- -
- - -

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

-
- -

参考

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/set/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/set/index.html deleted file mode 100644 index c66481647a..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/set/index.html +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: handler.set() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/set -tags: - - ECMAScript6 - - JavaScript - - Method - - Proxy - - Proxy拦截 -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/set ---- -
{{JSRef}}
- -

handler.set() 方法是设置属性值操作的捕获器。

- -
{{EmbedInteractiveExample("pages/js/proxyhandler-set.html", "taller")}}
- - - -

语法

- -
const p = new Proxy(target, {
-  set: function(target, property, value, receiver) {
-  }
-});
-
- -

参数

- -

以下是传递给 set() 方法的参数。this 绑定在 handler 对象上。

- -
-
target
-
目标对象。
-
property
-
将被设置的属性名或 {{jsxref("Symbol")}}。
-
value
-
新属性值。
-
receiver
-
最初被调用的对象。通常是 proxy 本身,但 handler 的 set 方法也有可能在原型链上,或以其他方式被间接地调用(因此不一定是 proxy 本身)。 -
-

比如:假设有一段代码执行 obj.name = "jen"obj 不是一个 proxy,且自身不含 name 属性,但是它的原型链上有一个 proxy,那么,那个 proxy 的 set() 处理器会被调用,而此时,obj 会作为 receiver 参数传进来。

-
-
-
- -

返回值

- -

set() 方法应当返回一个布尔值。

- - - -

描述

- -

handler.set() 方法用于拦截设置属性值的操作。

- -

拦截

- -

该方法会拦截目标对象的以下操作:

- - - -

约束

- -

如果违背以下的约束条件,proxy 会抛出一个 {{jsxref("TypeError")}} 异常:

- - - -

示例

- -

以下代码演示如何捕获属性的设置操作。

- -
var p = new Proxy({}, {
-  set: function(target, prop, value, receiver) {
-    target[prop] = value;
-    console.log('property set: ' + prop + ' = ' + value);
-    return true;
-  }
-})
-
-console.log('a' in p);  // false
-
-p.a = 10;               // "property set: a = 10"
-console.log('a' in p);  // true
-console.log(p.a);       // 10
- -

规范

- - - - - - - - - - - - -
规范
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-set-p-v-receiver', '[[Set]]')}}
- -

浏览器兼容性

- - - -

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

- -

另见

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/setprototypeof/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/setprototypeof/index.html deleted file mode 100644 index 9d88cd2593..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/handler/setprototypeof/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: handler.setPrototypeOf() -slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/setPrototypeOf -translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/setPrototypeOf ---- -
{{JSRef}}
- -

handler.setPrototypeOf() 方法主要用来拦截 {{jsxref("Object.setPrototypeOf()")}}.

- -

语法

- -
var p = new Proxy(target, {
-  setPrototypeOf: function(target, prototype) {
-  }
-});
-
- -

参数

- -

以下参数传递给 setPrototypeOf 方法. 

- -
-
target
-
被拦截目标对象.
-
prototype
-
对象新原型或为null.
-
- -

返回值

- -

如果成功修改了[[Prototype]]setPrototypeOf 方法返回 true,否则返回 false.

- -

描述

- -

这个 handler.setPrototypeOf 方法用于拦截 {{jsxref("Object.setPrototypeOf()")}}.

- -

拦截

- -

这个方法可以拦截以下操作:

- - - -

Invariants

- -

如果违反了下列规则,则proxy将抛出一个{{jsxref("TypeError")}}:

- - - -

示例

- -

如果你不想为你的对象设置一个新的原型,你的handler's的setPrototypeOf方法可以返回false,也可以抛出异常。

- -

The former approach means that any operation that performs such mutation, that throws an exception on failure to mutate, will have to create the exception itself.  For example, {{jsxref("Object.setPrototypeOf()")}} will create and throw a TypeError itself.  If the mutation is performed by an operation that doesn't ordinarily throw in case of failure, such as {{jsxref("Reflect.setPrototypeOf()")}}, no exception will be thrown.

- -
var handlerReturnsFalse = {
-    setPrototypeOf(target, newProto) {
-        return false;
-    }
-};
-
-var newProto = {}, target = {};
-
-var p1 = new Proxy(target, handlerReturnsFalse);
-Object.setPrototypeOf(p1, newProto); // throws a TypeError
-Reflect.setPrototypeOf(p1, newProto); // returns false
-
- -

The latter approach will cause any operation that attempts to mutate, to throw.  This approach is required if you want even non-throwing operations to throw on failure, or you want to throw a custom exception value.

- -
var handlerThrows = {
-    setPrototypeOf(target, newProto) {
-        throw new Error('custom error');
-    }
-};
-
-var newProto = {}, target = {};
-
-var p2 = new Proxy(target, handlerThrows);
-Object.setPrototypeOf(p2, newProto); // throws new Error("custom error")
-Reflect.setPrototypeOf(p2, newProto); // throws new Error("custom error")
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-setprototypeof-v', '[[SetPrototypeOf]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-setprototypeof-v', '[[SetPrototypeOf]]')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/apply/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/apply/index.html new file mode 100644 index 0000000000..62b8b67f5f --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/apply/index.html @@ -0,0 +1,117 @@ +--- +title: handler.apply() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply +tags: + - ECMAScript6 + - JavaScript + - Method + - Proxy +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply +--- +
{{JSRef}}
+ +

handler.apply() 方法用于拦截函数的调用。

+ +
{{EmbedInteractiveExample("pages/js/proxyhandler-apply.html", "taller")}}
+ + + +

语法

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

参数

+ +

以下是传递给apply方法的参数,this上下文绑定在handler对象上.

+ +
+
target
+
目标对象(函数)。
+
thisArg
+
被调用时的上下文对象。
+
argumentsList
+
被调用时的参数数组。
+
+ +

返回值

+ +

apply方法可以返回任何值。

+ +

描述

+ +

handler.apply 方法用于拦截函数的调用。

+ +

拦截

+ +

该方法会拦截目标对象的以下操作:

+ + + +

约束

+ +

如果违反了以下约束,代理将抛出一个TypeError:

+ +

target必须是可被调用的。也就是说,它必须是一个函数对象。

+ +

示例

+ +

以下代码演示如何捕获函数的调用。

+ +
var p = new Proxy(function() {}, {
+  apply: function(target, thisArg, argumentsList) {
+    console.log('called: ' + argumentsList.join(', '));
+    return argumentsList[0] + argumentsList[1] + argumentsList[2];
+  }
+});
+
+console.log(p(1, 2, 3)); // "called: 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')}} 
+ +

浏览器兼容性

+ +
+ + +

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

+
+ +

另见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/construct/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/construct/index.html new file mode 100644 index 0000000000..209e9752e3 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/construct/index.html @@ -0,0 +1,130 @@ +--- +title: handler.construct() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/construct +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/construct +--- +
{{JSRef}}
+ +

handler.construct() 方法用于拦截{{jsxref("Operators/new", "new")}} 操作符. 为了使new操作符在生成的Proxy对象上生效,用于初始化代理的目标对象自身必须具有[[Construct]]内部方法(即 new target 必须是有效的)。

+ +

{{EmbedInteractiveExample("pages/js/proxyhandler-construct.html", "taller")}}

+ +

语法

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

参数

+ +

下面的参数将会传递给construct方法,this绑定在handler上。

+ +
+
target
+
目标对象。
+
argumentsList
+
constructor的参数列表。
+
newTarget
+
最初被调用的构造函数,就上面的例子而言是p。
+
+ +

返回值

+ +

construct 方法必须返回一个对象。

+ +

描述

+ +

handler.construct() 方法用于拦截 {{jsxref("Operators/new", "new")}}操作符。

+ +

拦截

+ +

该拦截器可以拦截以下操作:

+ + + +

约束

+ +

如果违反以下约定,代理将会抛出错误 {{jsxref("TypeError")}}:

+ + + +

示例

+ +

下面代码演示如何拦截 {{jsxref("Operators/new", "new")}} 操作。

+ +
var p = new Proxy(function() {}, {
+  construct: function(target, argumentsList, newTarget) {
+    console.log('called: ' + argumentsList.join(', '));
+    return { value: argumentsList[0] * 10 };
+  }
+});
+
+console.log(new p(1).value); // "called: 1"
+                             // 10
+
+ +

下面的代码违反了约定.

+ +
var p = new Proxy(function() {}, {
+  construct: function(target, argumentsList, newTarget) {
+    return 1;
+  }
+});
+
+new p(); // TypeError is thrown
+
+ +

下面的代码未能正确的初始化Proxy。Proxy初始化时,传给它的target 必须具有一个有效的constructor供new操作符调用。

+ +
var p = new Proxy({}, {
+  construct: function(target, argumentsList, newTarget) {
+    return {};
+  }
+});
+
+new p(); // TypeError is thrown, "p" is not a constructor
+
+ +

规范

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

浏览器兼容性

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

相关主题

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/defineproperty/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/defineproperty/index.html new file mode 100644 index 0000000000..9912e043a0 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/defineproperty/index.html @@ -0,0 +1,181 @@ +--- +title: handler.defineProperty() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/defineProperty +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/defineProperty +--- +
{{JSRef}}
+ +

handler.defineProperty() 用于拦截对对象的 {{jsxref("Object.defineProperty()")}} 操作。

+ +

语法

+ +
var p = new Proxy(target, {
+  defineProperty: function(target, property, descriptor) {
+  }
+});
+
+ +

参数

+ +

下列参数将会被传递给 defineProperty 方法。 this 绑定在 handler 对象上。

+ +
+
target
+
目标对象。
+
property
+
待检索其描述的属性名。
+
descriptor
+
待定义或修改的属性的描述符。
+
+ +

返回值

+ +

defineProperty 方法必须以一个 {{jsxref("Boolean")}} 返回,表示定义该属性的操作成功与否。

+ +

描述

+ +

handler.defineProperty() 用于拦截对对象的 {{jsxref("Object.defineProperty()")}} 操作。

+ +

拦截

+ +

该方法会拦截目标对象的以下操作 :

+ + + +

不变量

+ +

如果违背了以下的不变量,proxy会抛出 {{jsxref("TypeError")}}:

+ + + +

示例

+ +

以下代码演示如何拦截对目标对象的 {{jsxref("Object.defineProperty()")}} 操作。

+ +
var p = new Proxy({}, {
+  defineProperty: function(target, prop, descriptor) {
+    console.log('called: ' + prop);
+    return true;
+  }
+});
+
+var desc = { configurable: true, enumerable: true, value: 10 };
+Object.defineProperty(p, 'a', desc); // "called: a"
+
+ +

当调用 {{jsxref("Object.defineProperty()")}} 或者 {{jsxref("Reflect.defineProperty()")}},传递给 definePropertydescriptor   有一个限制 - 只有以下属性才有用,非标准的属性将会被无视 :

+ + + +
var p = new Proxy({}, {
+  defineProperty(target, prop, descriptor) {
+    console.log(descriptor);
+    return Reflect.defineProperty(target, prop, descriptor);
+  }
+});
+
+Object.defineProperty(p, 'name', {
+  value: 'proxy',
+  type: 'custom'
+});  // { value: 'proxy' }
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc', '[[DefineOwnProperty]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc', '[[DefineOwnProperty]]')}}{{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/zh-cn/web/javascript/reference/global_objects/proxy/proxy/deleteproperty/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/deleteproperty/index.html new file mode 100644 index 0000000000..6cb4255755 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/deleteproperty/index.html @@ -0,0 +1,149 @@ +--- +title: handler.deleteProperty() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/deleteProperty +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/deleteProperty +--- +
{{JSRef}}
+ +

handler.deleteProperty() 方法用于拦截对对象属性的 {{jsxref("Operators/delete", "delete")}} 操作。

+ +

语法

+ +
var p = new Proxy(target, {
+  deleteProperty: function(target, property) {
+  }
+});
+
+ +

参数

+ +

deleteProperty 方法将会接受以下参数。 this 被绑定在 handler上。

+ +
+
target
+
目标对象。
+
property
+
待删除的属性名。
+
+ +

返回值

+ +

deleteProperty 必须返回一个 {{jsxref("Boolean")}} 类型的值,表示了该属性是否被成功删除。

+ +

描述

+ +

handler.deleteProperty() 方法可以拦截 {{jsxref("Operators/delete", "delete")}} 操作。

+ +

拦截

+ +

该方法会拦截以下操作:

+ + + +

不变量

+ +

如果违背了以下不变量,proxy 将会抛出一个 {{jsxref("TypeError")}}:

+ + + +

示例

+ +

以下代码演示了对 {{jsxref("Operators/delete", "delete")}} 操作的拦截。

+ +
var p = new Proxy({}, {
+  deleteProperty: function(target, prop) {
+    console.log('called: ' + prop);
+    return true;
+  }
+});
+
+delete p.a; // "called: a"
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-delete-p', '[[Delete]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-delete-p', '[[Delete]]')}}{{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/zh-cn/web/javascript/reference/global_objects/proxy/proxy/get/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/get/index.html new file mode 100644 index 0000000000..14a350436a --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/get/index.html @@ -0,0 +1,177 @@ +--- +title: handler.get() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/get +tags: + - ECMAScript6 + - JavaScript + - Method + - Proxy +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/get +--- +
{{JSRef}}
+ +

handler.get() 方法用于拦截对象的读取属性操作。

+ +

语法

+ +
var p = new Proxy(target, {
+  get: function(target, property, receiver) {
+  }
+});
+
+ +

参数

+ +

以下是传递给get方法的参数,this上下文绑定在handler对象上.

+ +
+
target
+
目标对象。
+
property
+
被获取的属性名。
+
receiver
+
Proxy或者继承Proxy的对象
+
+ +

返回值

+ +

get方法可以返回任何值。

+ +

描述

+ +

handler.get 方法用于拦截对象的读取属性操作。

+ +

拦截

+ +

该方法会拦截目标对象的以下操作:

+ + + +

约束

+ +

如果违背了以下的约束,proxy会抛出 {{jsxref("TypeError")}}:

+ + + +

示例

+ +

以下代码演示如何拦截属性值的读取操作。

+ +
var p = new Proxy({}, {
+  get: function(target, prop, receiver) {
+    console.log("called: " + prop);
+    return 10;
+  }
+});
+
+console.log(p.a); // "called: a"
+                  // 10
+
+ +

以下代码演示违反约束的情况。

+ +
var obj = {};
+Object.defineProperty(obj, "a", {
+  configurable: false,
+  enumerable: false,
+  value: 10,
+  writable: false
+});
+
+var p = new Proxy(obj, {
+  get: function(target, prop) {
+    return 20;
+  }
+});
+
+p.a; //会抛出TypeError
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver', '[[Get]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver', '[[Get]]')}}{{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/zh-cn/web/javascript/reference/global_objects/proxy/proxy/getownpropertydescriptor/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/getownpropertydescriptor/index.html new file mode 100644 index 0000000000..470b2c6ad9 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/getownpropertydescriptor/index.html @@ -0,0 +1,168 @@ +--- +title: handler.getOwnPropertyDescriptor() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/getOwnPropertyDescriptor +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/getOwnPropertyDescriptor +--- +
{{JSRef}}
+ +

handler.getOwnPropertyDescriptor() 方法是 {{jsxref("Object.getOwnPropertyDescriptor()")}}  的钩子。

+ +

语法

+ +
var p = new Proxy(target, {
+  getOwnPropertyDescriptor: function(target, prop) {
+  }
+});
+
+ +

参数

+ +

下列参数会被传入 getOwnPropertyDescriptor 方法中。这是绑定到handler上。 

+ +
+
target
+
目标对象。
+
prop
+
返回属性名称的描述。
+
+ +

返回值

+ +

getOwnPropertyDescriptor 方法必须返回一个 object 或 undefined

+ +

描述

+ +

handler.getOwnPropertyDescriptor() 方法是 {{jsxref("Object.getOwnPropertyDescriptor()")}} 的陷阱。

+ +

拦截

+ +

这个陷阱可以拦截这些操作:

+ + + +

不变量

+ +

如果下列不变量被违反,代理将抛出一个 {{jsxref("TypeError")}}:

+ + + +

示例

+ +

以下是 {{jsxref("Object.getOwnPropertyDescriptor()")}} 的代码陷阱:

+ +
var p = new Proxy({ a: 20}, {
+  getOwnPropertyDescriptor: function(target, prop) {
+    console.log('called: ' + prop);
+    return { configurable: true, enumerable: true, value: 10 };
+  }
+});
+
+console.log(Object.getOwnPropertyDescriptor(p, 'a').value); // "called: a"
+                                                            // 10
+
+ +

以下代码则违反了不变量。

+ +
var obj = { a: 10 };
+Object.preventExtensions(obj);
+var p = new Proxy(obj, {
+  getOwnPropertyDescriptor: function(target, prop) {
+    return undefined;
+  }
+});
+
+Object.getOwnPropertyDescriptor(p, 'a'); // TypeError is thrown
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p', '[[GetOwnProperty]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p', '[[GetOwnProperty]]')}}{{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/zh-cn/web/javascript/reference/global_objects/proxy/proxy/getprototypeof/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/getprototypeof/index.html new file mode 100644 index 0000000000..215d2d9646 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/getprototypeof/index.html @@ -0,0 +1,141 @@ +--- +title: handler.getPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/getPrototypeOf +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Proxy + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/getPrototypeOf +--- +
{{JSRef("Global_Objects", "Proxy")}}
+ +

handler.getPrototypeOf() 是一个代理(Proxy)方法,当读取代理对象的原型时,该方法就会被调用。

+ +
{{EmbedInteractiveExample("pages/js/proxyhandler-getprototypeof.html", "taller")}}
+ + + +

语法

+ +
const p = new Proxy(obj, {
+  getPrototypeOf(target) {
+  ...
+  }
+});
+
+ +

参数

+ +

getPrototypeOf 方法被调用时,this 指向的是它所属的处理器对象。

+ +
+
target
+
被代理的目标对象。
+
+ +

返回值

+ +

getPrototypeOf 方法的返回值必须是一个对象或者 null

+ +

描述

+ +

在 JavaScript 中,下面这五种操作(方法/属性/运算符)可以触发 JS 引擎读取一个对象的原型,也就是可以触发 getPrototypeOf() 代理方法的运行:

+ + + +

如果遇到了下面两种情况,JS 引擎会抛出 {{jsxref("TypeError")}} 异常:

+ + + +

示例

+ +

基本用法

+ +
var obj = {};
+var proto = {};
+var handler = {
+    getPrototypeOf(target) {
+        console.log(target === obj);   // true
+        console.log(this === handler); // true
+        return proto;
+    }
+};
+
+var p = new Proxy(obj, handler);
+console.log(Object.getPrototypeOf(p) === proto);    // true
+
+ +

5 种触发 getPrototypeOf 代理方法的方式

+ +
var obj = {};
+var p = new Proxy(obj, {
+    getPrototypeOf(target) {
+        return Array.prototype;
+    }
+});
+console.log(
+    Object.getPrototypeOf(p) === Array.prototype,  // true
+    Reflect.getPrototypeOf(p) === Array.prototype, // true
+    p.__proto__ === Array.prototype,               // true
+    Array.prototype.isPrototypeOf(p),              // true
+    p instanceof Array                             // true
+);
+
+ +

两种情况下的异常

+ +
var obj = {};
+var p = new Proxy(obj, {
+    getPrototypeOf(target) {
+        return "foo";
+    }
+});
+Object.getPrototypeOf(p); // TypeError: "foo" is not an object or null
+
+var obj = Object.preventExtensions({});
+var p = new Proxy(obj, {
+    getPrototypeOf(target) {
+        return {};
+    }
+});
+Object.getPrototypeOf(p); // TypeError: expected same prototype value
+
+ +

规范

+ + + + + + + + + + +
规范
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof', '[[GetPrototypeOf]]')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/has/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/has/index.html new file mode 100644 index 0000000000..fead0846ff --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/has/index.html @@ -0,0 +1,176 @@ +--- +title: handler.has() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/has +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/has +--- +
{{JSRef}}
+ +

 handler.has() 方法是针对 {{jsxref("Operators/in", "in")}} 操作符的代理方法。

+ + + + + +

{{EmbedInteractiveExample("pages/js/proxyhandler-has.html", "taller")}}

+ + + + + +

语法

+ +
var p = new Proxy(target, {
+  has: function(target, prop) {
+  }
+});
+
+ +

参数

+ +

下面是传递给 has 方法的参数. this is bound to the handler.

+ +
+
target
+
目标对象.
+
prop
+
需要检查是否存在的属性.
+
+ +

返回值

+ +

has 方法返回一个 boolean 属性的值.

+ +

描述

+ +

handler.has 方法可以看作是针对 {{jsxref("Operators/in", "in")}} 操作的钩子.

+ +

拦截

+ +

这个钩子可以拦截下面这些操作:

+ + + +

约束

+ +

如果违反了下面这些规则,  proxy 将会抛出 {{jsxref("TypeError")}}:

+ + + +

示例

+ +

下面的代码拦截了 {{jsxref("Operators/in", "in")}} 操作符.

+ +
var p = new Proxy({}, {
+  has: function(target, prop) {
+    console.log('called: ' + prop);
+    return true;
+  }
+});
+
+console.log('a' in p); // "called: a"
+                       // true
+
+ +

下面的代码违反了约束.

+ +
var obj = { a: 10 };
+Object.preventExtensions(obj);
+var p = new Proxy(obj, {
+  has: function(target, prop) {
+    return false;
+  }
+});
+
+'a' in p; // TypeError is thrown
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-hasproperty-p', '[[HasProperty]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-hasproperty-p', '[[HasProperty]]')}}{{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/zh-cn/web/javascript/reference/global_objects/proxy/proxy/isextensible/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/isextensible/index.html new file mode 100644 index 0000000000..7be418197f --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/isextensible/index.html @@ -0,0 +1,123 @@ +--- +title: handler.isExtensible() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/isExtensible +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Proxy +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/isExtensible +--- +
{{JSRef}}
+handler.isExtensible() 方法用于拦截对对象的Object.isExtensible()。
+ +
+

{{EmbedInteractiveExample("pages/js/proxyhandler-isextensible.html", "taller")}}

+
+ +

语法

+ +
var p = new Proxy(target, {
+  isExtensible: function(target) {
+  }
+});
+
+ +

参数

+ +

下列参数将会被传递给 isExtensible方法。 this 绑定在 handler 对象上。

+ +
+
target
+
目标对象。
+
+ +

返回值

+ +

isExtensible方法必须返回一个 Boolean值或可转换成Boolean的值。

+ +

描述

+ +

handler.isExtensible()用于拦截对对象的Object.isExtensible()。

+ +

拦截

+ +

该方法会拦截目标对象的以下操作:

+ + + +

约束

+ +

如果违背了以下的约束,proxy会抛出 TypeError:

+ + + +

示例

+ +

以下代码演示{{jsxref("Object.isExtensible()")}}.

+ +
var p = new Proxy({}, {
+  isExtensible: function(target) {
+    console.log('called');
+    return true;//也可以return 1;等表示为true的值
+  }
+});
+
+console.log(Object.isExtensible(p)); // "called"
+                                     // true
+
+ +

以下代码演示违反约束的情况。

+ +
var p = new Proxy({}, {
+  isExtensible: function(target) {
+    return false;//return 0;return NaN等都会报错
+  }
+});
+
+Object.isExtensible(p); // TypeError is thrown
+
+ +

规范

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

浏览器兼容性

+ +
+ + +

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

+
+ +

另见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/ownkeys/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/ownkeys/index.html new file mode 100644 index 0000000000..956b908375 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/ownkeys/index.html @@ -0,0 +1,193 @@ +--- +title: handler.ownKeys() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/ownKeys +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/ownKeys +--- +
{{JSRef}}
+ +

handler.ownKeys() 方法用于拦截 {{jsxref("Reflect.ownKeys()")}}.

+ + + +

{{EmbedInteractiveExample("pages/js/proxyhandler-ownkeys.html", "taller")}}

+ + + +

语法

+ +
var p = new Proxy(target, {
+  ownKeys: function(target) {
+  }
+});
+
+ +

参数

+ +

下面的参数被传递给ownKeys。this被绑定在handler上。

+ +
+
target
+
目标对象.
+
+ +

返回值

+ +

ownKeys 方法必须返回一个可枚举对象.

+ +

描述

+ +

handler.ownKeys() 方法用于拦截 {{jsxref("Reflect.ownKeys()")}}.

+ +

拦截

+ +

该拦截器可以拦截以下操作::

+ + + +

约束

+ +

如果违反了下面的约束,proxy将抛出错误 {{jsxref("TypeError")}}:

+ + + +

示例

+ +

下面的代码拦截 {{jsxref("Object.getOwnPropertyNames()")}}.

+ +
var p = new Proxy({}, {
+  ownKeys: function(target) {
+    console.log('called');
+    return ['a', 'b', 'c'];
+  }
+});
+
+console.log(Object.getOwnPropertyNames(p)); // "called"
+                                            // [ 'a', 'b', 'c' ]
+ +

下面的代码违反了约定

+ +
var obj = {};
+Object.defineProperty(obj, 'a', {
+  configurable: false,
+  enumerable: true,
+  value: 10 }
+);
+
+var p = new Proxy(obj, {
+  ownKeys: function(target) {
+    return [123, 12.5, true, false, undefined, null, {}, []];
+  }
+});
+
+console.log(Object.getOwnPropertyNames(p));
+
+// TypeError: proxy [[OwnPropertyKeys]] 必须返回一个数组
+// 数组元素类型只能是String或Symbol
+
+ +

标准

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys', '[[OwnPropertyKeys]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys', '[[OwnPropertyKeys]]')}}{{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}}
+
+ +

兼容性注意事项

+ +

Firefox火狐

+ + + +

另见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/preventextensions/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/preventextensions/index.html new file mode 100644 index 0000000000..dd6823c9dd --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/preventextensions/index.html @@ -0,0 +1,120 @@ +--- +title: handler.preventExtensions() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/preventExtensions +tags: + - Proxy 代理 拦截 +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/preventExtensions +--- +
{{JSRef}}
+ +

handler.preventExtensions() 方法用于设置对{{jsxref("Object.preventExtensions()")}}的拦截

+ +

{{EmbedInteractiveExample("pages/js/proxyhandler-preventextensions.html", "taller")}}

+ +

语法

+ +
var p = new Proxy(target, {
+  preventExtensions: function(target) {
+  }
+});
+
+ +

参数

+ +

以下参数传递给 preventExtensions 方法. 它会绑定到这个handler.

+ +
+
target
+
所要拦截的目标对象.
+
+ +

返回值

+ +

preventExtensions 方法返回一个布尔值.

+ +

描述

+ +

handler.preventExtensions() 拦截 {{jsxref("Object.preventExtensions()")}}返回一个布尔值.

+ +

拦截

+ +

这个trap可以拦截这些操作:

+ + + +

约束

+ +

如果违反了下列规则, proxy则会抛出一个 {{jsxref("TypeError")}}:

+ + + +

示例

+ +

以下代码演示了如何拦截{{jsxref("Object.preventExtensions()")}}。

+ +
var p = new Proxy({}, {
+  preventExtensions: function(target) {
+    console.log('called');
+    Object.preventExtensions(target);
+    return true;
+  }
+});
+
+console.log(Object.preventExtensions(p)); // "called"
+                                          // false
+
+ +

以下代码违反了约束.

+ +
var p = new Proxy({}, {
+  preventExtensions: function(target) {
+    return true;
+  }
+});
+
+Object.preventExtensions(p); // 抛出类型错误
+
+ +

规范

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

浏览器兼容性

+ +
+ + +

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

+
+ +

参考

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/set/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/set/index.html new file mode 100644 index 0000000000..c66481647a --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/set/index.html @@ -0,0 +1,125 @@ +--- +title: handler.set() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/set +tags: + - ECMAScript6 + - JavaScript + - Method + - Proxy + - Proxy拦截 +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/set +--- +
{{JSRef}}
+ +

handler.set() 方法是设置属性值操作的捕获器。

+ +
{{EmbedInteractiveExample("pages/js/proxyhandler-set.html", "taller")}}
+ + + +

语法

+ +
const p = new Proxy(target, {
+  set: function(target, property, value, receiver) {
+  }
+});
+
+ +

参数

+ +

以下是传递给 set() 方法的参数。this 绑定在 handler 对象上。

+ +
+
target
+
目标对象。
+
property
+
将被设置的属性名或 {{jsxref("Symbol")}}。
+
value
+
新属性值。
+
receiver
+
最初被调用的对象。通常是 proxy 本身,但 handler 的 set 方法也有可能在原型链上,或以其他方式被间接地调用(因此不一定是 proxy 本身)。 +
+

比如:假设有一段代码执行 obj.name = "jen"obj 不是一个 proxy,且自身不含 name 属性,但是它的原型链上有一个 proxy,那么,那个 proxy 的 set() 处理器会被调用,而此时,obj 会作为 receiver 参数传进来。

+
+
+
+ +

返回值

+ +

set() 方法应当返回一个布尔值。

+ + + +

描述

+ +

handler.set() 方法用于拦截设置属性值的操作。

+ +

拦截

+ +

该方法会拦截目标对象的以下操作:

+ + + +

约束

+ +

如果违背以下的约束条件,proxy 会抛出一个 {{jsxref("TypeError")}} 异常:

+ + + +

示例

+ +

以下代码演示如何捕获属性的设置操作。

+ +
var p = new Proxy({}, {
+  set: function(target, prop, value, receiver) {
+    target[prop] = value;
+    console.log('property set: ' + prop + ' = ' + value);
+    return true;
+  }
+})
+
+console.log('a' in p);  // false
+
+p.a = 10;               // "property set: a = 10"
+console.log('a' in p);  // true
+console.log(p.a);       // 10
+ +

规范

+ + + + + + + + + + + + +
规范
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-set-p-v-receiver', '[[Set]]')}}
+ +

浏览器兼容性

+ + + +

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

+ +

另见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/setprototypeof/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/setprototypeof/index.html new file mode 100644 index 0000000000..9d88cd2593 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/setprototypeof/index.html @@ -0,0 +1,124 @@ +--- +title: handler.setPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/setPrototypeOf +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/setPrototypeOf +--- +
{{JSRef}}
+ +

handler.setPrototypeOf() 方法主要用来拦截 {{jsxref("Object.setPrototypeOf()")}}.

+ +

语法

+ +
var p = new Proxy(target, {
+  setPrototypeOf: function(target, prototype) {
+  }
+});
+
+ +

参数

+ +

以下参数传递给 setPrototypeOf 方法. 

+ +
+
target
+
被拦截目标对象.
+
prototype
+
对象新原型或为null.
+
+ +

返回值

+ +

如果成功修改了[[Prototype]]setPrototypeOf 方法返回 true,否则返回 false.

+ +

描述

+ +

这个 handler.setPrototypeOf 方法用于拦截 {{jsxref("Object.setPrototypeOf()")}}.

+ +

拦截

+ +

这个方法可以拦截以下操作:

+ + + +

Invariants

+ +

如果违反了下列规则,则proxy将抛出一个{{jsxref("TypeError")}}:

+ + + +

示例

+ +

如果你不想为你的对象设置一个新的原型,你的handler's的setPrototypeOf方法可以返回false,也可以抛出异常。

+ +

The former approach means that any operation that performs such mutation, that throws an exception on failure to mutate, will have to create the exception itself.  For example, {{jsxref("Object.setPrototypeOf()")}} will create and throw a TypeError itself.  If the mutation is performed by an operation that doesn't ordinarily throw in case of failure, such as {{jsxref("Reflect.setPrototypeOf()")}}, no exception will be thrown.

+ +
var handlerReturnsFalse = {
+    setPrototypeOf(target, newProto) {
+        return false;
+    }
+};
+
+var newProto = {}, target = {};
+
+var p1 = new Proxy(target, handlerReturnsFalse);
+Object.setPrototypeOf(p1, newProto); // throws a TypeError
+Reflect.setPrototypeOf(p1, newProto); // returns false
+
+ +

The latter approach will cause any operation that attempts to mutate, to throw.  This approach is required if you want even non-throwing operations to throw on failure, or you want to throw a custom exception value.

+ +
var handlerThrows = {
+    setPrototypeOf(target, newProto) {
+        throw new Error('custom error');
+    }
+};
+
+var newProto = {}, target = {};
+
+var p2 = new Proxy(target, handlerThrows);
+Object.setPrototypeOf(p2, newProto); // throws new Error("custom error")
+Reflect.setPrototypeOf(p2, newProto); // throws new Error("custom error")
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-setprototypeof-v', '[[SetPrototypeOf]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-setprototypeof-v', '[[SetPrototypeOf]]')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/rangeerror/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/rangeerror/prototype/index.html deleted file mode 100644 index 0e2c78aedf..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/rangeerror/prototype/index.html +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: RangeError.prototype -slug: Web/JavaScript/Reference/Global_Objects/RangeError/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/RangeError -translation_of_original: Web/JavaScript/Reference/Global_Objects/RangeError/prototype ---- -
{{JSRef}}
- -
 
- -
RangeError.prototype 属性表示 {{jsxref("RangeError")}} 构造函数的原型。
- -
 
- -
{{js_property_attributes(0, 0, 0)}}
- -

描述

- -

所有  {{jsxref("RangeError")}} 的实例都继承自 RangeError.prototype ,所以你可以使用这个属性来为所有的实例添加属性或方法。

- -

属性

- -
-
RangeError.prototype.constructor
-
指定了创建实例原型的函数
-
{{jsxref("Error.prototype.message", "RangeError.prototype.message")}}
-
错误信息。尽管 ECMA-262 规定了 {{jsxref("RangeError")}} 应该拥有一个 message 属性,但在 SpiderMonkey 中,该属性继承自 {{jsxref("Error.prototype.message")}}。
-
{{jsxref("Error.prototype.name", "RangeError.prototype.name")}}
-
错误名字,继承自 {{jsxref("Error")}}。
-
{{jsxref("Error.prototype.fileName", "RangeError.prototype.fileName")}}
-
引起该错误的文件路径,继承自 {{jsxref("Error")}}。
-
{{jsxref("Error.prototype.lineNumber", "RangeError.prototype.lineNumber")}}
-
引起该错误的行号,继承自 {{jsxref("Error")}}。
-
{{jsxref("Error.prototype.columnNumber", "RangeError.prototype.columnNumber")}}
-
引起该错误的列号,继承自 {{jsxref("Error")}}。
-
{{jsxref("Error.prototype.stack", "RangeError.prototype.stack")}}
-
堆栈跟踪记录,继承自 {{jsxref("Error")}}。
-
- -

方法

- -

尽管 {{jsxref("RangeError")}} 原型对象自身没有包含任何方法,但是 {{jsxref("RangeError")}} 实例却通过原型链继承到了一些方法。

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.11.7.6', 'NativeError.prototype')}}{{Spec2('ES5.1')}}Defined as NativeError.prototype.
{{SpecName('ES6', '#sec-nativeerror.prototype', 'NativeError.prototype')}}{{Spec2('ES6')}}Defined as NativeError.prototype.
{{SpecName('ESDraft', '#sec-nativeerror.prototype', 'NativeError.prototype')}}{{Spec2('ESDraft')}}Defined as NativeError.prototype.
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.RangeError")}}

-
- -

See also

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/referenceerror/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/referenceerror/prototype/index.html deleted file mode 100644 index 4cb00496ef..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/referenceerror/prototype/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: ReferenceError.prototype -slug: Web/JavaScript/Reference/Global_Objects/ReferenceError/prototype -tags: - - Error - - JavaScript - - Property - - Prototype - - ReferenceError -translation_of: Web/JavaScript/Reference/Global_Objects/ReferenceError -translation_of_original: Web/JavaScript/Reference/Global_Objects/ReferenceError/prototype ---- -
{{JSRef}}
- -

ReferenceError.prototype 表示 {{jsxref("ReferenceError")}} 的原型构造器。

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

描述

- -

所有{{jsxref("ReferenceError")}} 实例都继承自 ReferenceError.prototype. 你可以使用原型来为所有实例添加属性和方法。

- -

属性

- -
-
ReferenceError.prototype.constructor
-
创建一个实例原型的函数。
-
{{jsxref("Error.prototype.message", "ReferenceError.prototype.message")}}
-
错误信息。尽管ECMA-262 曾表示 {{jsxref("ReferenceError")}} 应该提供自己的 message 属性, 在 SpiderMonkey 中, 它继承自{{jsxref("Error.prototype.message")}}.
-
{{jsxref("Error.prototype.name", "ReferenceError.prototype.name")}}
-
错误名称. 继承自{{jsxref("Error")}}.
-
{{jsxref("Error.prototype.fileName", "ReferenceError.prototype.fileName")}}
-
出现这个错误的路径. 继承自 {{jsxref("Error")}}.
-
{{jsxref("Error.prototype.lineNumber", "ReferenceError.prototype.lineNumber")}}
-
出现这个错误的行号. 继承自 {{jsxref("Error")}}.
-
{{jsxref("Error.prototype.columnNumber", "ReferenceError.prototype.columnNumber")}}
-
出现这个错误的列号. 继承自 {{jsxref("Error")}}.
-
{{jsxref("Error.prototype.stack", "ReferenceError.prototype.stack")}}
-
堆栈追踪. 继承自 {{jsxref("Error")}}.
-
- -

方法

- -

尽管 {{jsxref("ReferenceError")}} 原型对象自身没有包括任何方法, {{jsxref("ReferenceError")}} 实例确实从原型链中继承了一些方法。

- -

规格

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
规格版本状态注释
{{SpecName('ES3')}}{{Spec2('ES3')}}初始定义
{{SpecName('ES5.1', '#sec-15.11.7.6', 'NativeError.prototype')}}{{Spec2('ES5.1')}} -

Defined as NativeError.prototype.

-
{{SpecName('ES6', '#sec-nativeerror.prototype', 'NativeError.prototype')}}{{Spec2('ES6')}}Defined as NativeError.prototype.
{{SpecName('ESDraft', '#sec-nativeerror.prototype', 'NativeError.prototype')}}{{Spec2('ESDraft')}}Defined as NativeError.prototype.
- -

浏览器兼容性

- -
- - -

{{Compat("javascript.builtins.ReferenceError")}}

-
- -

参见

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/reflect/comparing_reflect_and_object_methods/index.html b/files/zh-cn/web/javascript/reference/global_objects/reflect/comparing_reflect_and_object_methods/index.html new file mode 100644 index 0000000000..43023eae7f --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/reflect/comparing_reflect_and_object_methods/index.html @@ -0,0 +1,134 @@ +--- +title: 比较 Reflect 和 Object 方法 +slug: Web/JavaScript/Reference/Global_Objects/Reflect/比较_Reflect_和_Object_方法 +tags: + - Guide + - JavaScript + - Object + - Overview + - Reflect +translation_of: >- + Web/JavaScript/Reference/Global_Objects/Reflect/Comparing_Reflect_and_Object_methods +--- +
{{jssidebar}}
+ +

ES2015中引入的 {{jsxref("Reflect")}} 对象是一个内置对象,提供了与JavaScript对象交互的方法。Reflect 上存在的一些静态函数也对应于ES2015之前的{{jsxref("Object")}}上可用的方法。尽管某些方法在行为上看似相似,但它们之间常常存在细微的差异。

+ +

下表详细介绍了Object 和 Reflect API上可用方法之间的差异。请注意,如果API中不存在某种方法,则将其标记为N/A。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Method NameObjectReflect
defineProperty() +

{{jsxref("Object.defineProperty()")}} 返回传递给函数的对象。如果未在对象上成功定义属性,则返回TypeError

+
+

如果在对象上定义了属性,则{{jsxref("Reflect.defineProperty()")}}返回true,否则返回false

+
defineProperties() +

{{jsxref("Object.defineProperties()")}} 返回传递给函数的对象。如果未在对象上成功定义属性,则返回TypeError

+
N/A
set()N/A +

如果在对象上成功设置了属性,则{{jsxref("Reflect.set()")}}返回true,否则返回false。如果目标不是Object,则抛出TypeError

+
get()N/A +

{{jsxref("Reflect.get()")}}返回属性的值。如果目标不是Object,则抛出TypeError

+
deleteProperty()N/A +

如果属性从对象中删除,则{{jsxref("Reflect.deleteProperty()")}}返回true,否则返回false

+
getOwnPropertyDescriptor() +

如果传入的对象参数上存在{{jsxref("Object.getOwnPropertyDescriptor()")}} ,则会返回给定属性的属性描述符,如果不存在,则返回undefined

+
+

如果给定属性存在于对象上,则{{jsxref("Reflect.getOwnPropertyDescriptor()")}} 返回给定属性的属性描述符。如果不存在则返回undefined,如果传入除对象(原始值)以外的任何东西作为第一个参数,则返回TypeError

+
getOwnPropertyDescriptors() +

{{jsxref("Object.getOwnPropertyDescriptors()")}} 返回一个对象,其中包含每个传入对象的属性描述符。如果传入的对象没有拥有的属性描述符,则返回一个空对象。

+
N/A
getPrototypeOf() +

{{jsxref("Object.getPrototypeOf()")}}返回给定对象的原型。如果没有继承的原型,则返回null。在ES5中为非对象抛出TypeError,但在ES2015中强制为非对象。

+
+

{{jsxref("Reflect.getPrototypeOf()")}}返回给定对象的原型。如果没有继承的原型,则返回null,并为非对象抛出TypeError

+
setPrototypeOf() +

如果对象的原型设置成功,则{{jsxref("Object.setPrototypeOf()")}}返回对象本身。如果设置的原型不是Objectnull,或者被修改的对象的原型不可扩展,则抛出TypeError

+
+

如果在对象上成功设置了原型,则{{jsxref("Reflect.setPrototypeOf()")}} 返回true,否则返回false(包括原型是否不可扩展)。如果传入的目标不是Object,或者设置的原型不是Objectnull,则抛出TypeError

+
isExtensible() +

如果对象是可扩展的,则Object.isExtensible()返回true,否则返回false。如果第一个参数不是对象(原始值),则在ES5中抛出TypeError。在ES2015中,它将被强制为不可扩展的普通对象并返回false

+
+

如果对象是可扩展的,则{{jsxref("Reflect.isExtensible()")}} 返回true,否则返回false。如果第一个参数不是对象(原始值),则抛出TypeError

+
preventExtensions() +

{{jsxref("Object.preventExtensions()")}} 返回被设为不可扩展的对象。如果参数不是对象(原始值),则在ES5中抛出TypeError。在ES2015中,参数如为不可扩展的普通对象,然后返回对象本身。

+
+

returns true if the object has been made non-extensible, and false if it has not. Throws a TypeError if the argument is not an object (a primitive).

+ +

如果对象已变得不可扩展,则{{jsxref("Reflect.preventExtensions()")}} 返回true,否则返回false。如果参数不是对象(原始值),则抛出TypeError

+
keys() +

{{jsxref("Object.keys()")}}返回一个字符串数组,该字符串映射到目标对象自己的(可枚举)属性键。如果目标不是对象,则在ES5中抛出TypeError,但将非对象目标强制为ES2015中的对象

+
N/A
ownKeys()N/A +

{{jsxref("Reflect.ownKeys()")}}返回一个属性名称数组,该属性名称映射到目标对象自己的属性键。如果目标不是Object,则抛出TypeError

+
diff --git "a/files/zh-cn/web/javascript/reference/global_objects/reflect/\346\257\224\350\276\203_reflect_\345\222\214_object_\346\226\271\346\263\225/index.html" "b/files/zh-cn/web/javascript/reference/global_objects/reflect/\346\257\224\350\276\203_reflect_\345\222\214_object_\346\226\271\346\263\225/index.html" deleted file mode 100644 index 43023eae7f..0000000000 --- "a/files/zh-cn/web/javascript/reference/global_objects/reflect/\346\257\224\350\276\203_reflect_\345\222\214_object_\346\226\271\346\263\225/index.html" +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: 比较 Reflect 和 Object 方法 -slug: Web/JavaScript/Reference/Global_Objects/Reflect/比较_Reflect_和_Object_方法 -tags: - - Guide - - JavaScript - - Object - - Overview - - Reflect -translation_of: >- - Web/JavaScript/Reference/Global_Objects/Reflect/Comparing_Reflect_and_Object_methods ---- -
{{jssidebar}}
- -

ES2015中引入的 {{jsxref("Reflect")}} 对象是一个内置对象,提供了与JavaScript对象交互的方法。Reflect 上存在的一些静态函数也对应于ES2015之前的{{jsxref("Object")}}上可用的方法。尽管某些方法在行为上看似相似,但它们之间常常存在细微的差异。

- -

下表详细介绍了Object 和 Reflect API上可用方法之间的差异。请注意,如果API中不存在某种方法,则将其标记为N/A。

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Method NameObjectReflect
defineProperty() -

{{jsxref("Object.defineProperty()")}} 返回传递给函数的对象。如果未在对象上成功定义属性,则返回TypeError

-
-

如果在对象上定义了属性,则{{jsxref("Reflect.defineProperty()")}}返回true,否则返回false

-
defineProperties() -

{{jsxref("Object.defineProperties()")}} 返回传递给函数的对象。如果未在对象上成功定义属性,则返回TypeError

-
N/A
set()N/A -

如果在对象上成功设置了属性,则{{jsxref("Reflect.set()")}}返回true,否则返回false。如果目标不是Object,则抛出TypeError

-
get()N/A -

{{jsxref("Reflect.get()")}}返回属性的值。如果目标不是Object,则抛出TypeError

-
deleteProperty()N/A -

如果属性从对象中删除,则{{jsxref("Reflect.deleteProperty()")}}返回true,否则返回false

-
getOwnPropertyDescriptor() -

如果传入的对象参数上存在{{jsxref("Object.getOwnPropertyDescriptor()")}} ,则会返回给定属性的属性描述符,如果不存在,则返回undefined

-
-

如果给定属性存在于对象上,则{{jsxref("Reflect.getOwnPropertyDescriptor()")}} 返回给定属性的属性描述符。如果不存在则返回undefined,如果传入除对象(原始值)以外的任何东西作为第一个参数,则返回TypeError

-
getOwnPropertyDescriptors() -

{{jsxref("Object.getOwnPropertyDescriptors()")}} 返回一个对象,其中包含每个传入对象的属性描述符。如果传入的对象没有拥有的属性描述符,则返回一个空对象。

-
N/A
getPrototypeOf() -

{{jsxref("Object.getPrototypeOf()")}}返回给定对象的原型。如果没有继承的原型,则返回null。在ES5中为非对象抛出TypeError,但在ES2015中强制为非对象。

-
-

{{jsxref("Reflect.getPrototypeOf()")}}返回给定对象的原型。如果没有继承的原型,则返回null,并为非对象抛出TypeError

-
setPrototypeOf() -

如果对象的原型设置成功,则{{jsxref("Object.setPrototypeOf()")}}返回对象本身。如果设置的原型不是Objectnull,或者被修改的对象的原型不可扩展,则抛出TypeError

-
-

如果在对象上成功设置了原型,则{{jsxref("Reflect.setPrototypeOf()")}} 返回true,否则返回false(包括原型是否不可扩展)。如果传入的目标不是Object,或者设置的原型不是Objectnull,则抛出TypeError

-
isExtensible() -

如果对象是可扩展的,则Object.isExtensible()返回true,否则返回false。如果第一个参数不是对象(原始值),则在ES5中抛出TypeError。在ES2015中,它将被强制为不可扩展的普通对象并返回false

-
-

如果对象是可扩展的,则{{jsxref("Reflect.isExtensible()")}} 返回true,否则返回false。如果第一个参数不是对象(原始值),则抛出TypeError

-
preventExtensions() -

{{jsxref("Object.preventExtensions()")}} 返回被设为不可扩展的对象。如果参数不是对象(原始值),则在ES5中抛出TypeError。在ES2015中,参数如为不可扩展的普通对象,然后返回对象本身。

-
-

returns true if the object has been made non-extensible, and false if it has not. Throws a TypeError if the argument is not an object (a primitive).

- -

如果对象已变得不可扩展,则{{jsxref("Reflect.preventExtensions()")}} 返回true,否则返回false。如果参数不是对象(原始值),则抛出TypeError

-
keys() -

{{jsxref("Object.keys()")}}返回一个字符串数组,该字符串映射到目标对象自己的(可枚举)属性键。如果目标不是对象,则在ES5中抛出TypeError,但将非对象目标强制为ES2015中的对象

-
N/A
ownKeys()N/A -

{{jsxref("Reflect.ownKeys()")}}返回一个属性名称数组,该属性名称映射到目标对象自己的属性键。如果目标不是Object,则抛出TypeError

-
diff --git a/files/zh-cn/web/javascript/reference/global_objects/regexp/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/regexp/prototype/index.html deleted file mode 100644 index 0c76cb77ac..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/regexp/prototype/index.html +++ /dev/null @@ -1,153 +0,0 @@ ---- -title: RegExp.prototype -slug: Web/JavaScript/Reference/Global_Objects/RegExp/prototype -tags: - - JavaScript - - Property - - RegExp -translation_of: Web/JavaScript/Reference/Global_Objects/RegExp -translation_of_original: Web/JavaScript/Reference/Global_Objects/RegExp/prototype ---- -

{{JSRef("Global_Objects", "RegExp")}}

-

概述

-

RegExp.prototype 属性表示 {{jsxref("Global_Objects/RegExp", "RegExp")}} 构造函数的原型对象。

-

描述

-

查看 {{jsxref("Global_Objects/RegExp", "RegExp")}} 了解更多关于 RegExp 实例的说明。

-

RegExp 实例继承 RegExp.prototype。修改该原型对象上的属性或方法会影响到所有的 RegExp 实例。

-

属性

-

查看已废弃的RegExp属性

-

注意,RegExp 对象的几个属性既有完整的长属性名,也有对应的类 Perl 的短属性名。两个属性都有着同样的值。JavaScript 的正则语法就是基于 Perl 的。

-
-
- RegExp.prototype.constructor
-
- 创建该正则对象的构造函数。
-
- {{jsxref("RegExp.prototype.global")}}
-
- 是否开启全局匹配,也就是匹配目标字符串中所有可能的匹配项,而不是只进行第一次匹配。
-
- {{jsxref("RegExp.prototype.ignoreCase")}}
-
- 在匹配字符串时是否要忽略字符的大小写。
-
- {{jsxref("RegExp.prototype.lastIndex")}}
-
- 下次匹配开始的字符串索引位置。
-
- {{jsxref("RegExp.prototype.multiline")}}
-
- 是否开启多行模式匹配(影响 ^ 和 $ 的行为)。
-
- {{jsxref("RegExp.prototype.source")}}
-
- 正则对象的源模式文本。
-
- {{jsxref("RegExp.prototype.sticky")}} {{experimental_inline}}
-
- 是否开启粘滞匹配。
-
-
- {{ jsOverrides("Object", "properties", "constructor", "global", "ignoreCase", "lastIndex", "multiline", "source", "sticky") }}
-

方法

-

查看已废弃的RegExp方法

-
-
- {{jsxref("RegExp.prototype.exec()")}}
-
- 在目标字符串中执行一次正则匹配操作。
-
- {{jsxref("RegExp.prototype.test()")}}
-
- 测试当前正则是否能匹配目标字符串。
-
- {{jsxref("RegExp.prototype.toSource()")}} {{non-standard_inline}}
-
- 返回一个字符串,其值为该正则对象的字面量形式。覆盖了Object.prototype.toSource 方法.
-
- {{jsxref("RegExp.prototype.toString()")}}
-
- 返回一个字符串,其值为该正则对象的字面量形式。覆盖了{{jsxref("Object.prototype.toString()")}} 方法。
-
-
- {{ jsOverrides("Object", "Methods", "exec", "test", "toSource", "toString") }}
-

规范

- - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 1st Edition. Implemented in JavaScript 1.1StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.10.5.1', 'RegExp')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-regexp.prototype', 'RegExp.prototype')}}{{Spec2('ES6')}} 
-

浏览器兼容性

-

{{ 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/zh-cn/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html deleted file mode 100644 index ccb6f2df65..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: SharedArrayBuffer.prototype -slug: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/prototype -tags: - - Prototype - - SharedArrayBuffer -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)")}}
-
返回一个新的SharedArrayBuffer,其内容是此SharedArrayBuffer字节从beigin开始(包括begin)到end结束(不包括end)的副本。 如果beginend为负,则它是指数组末尾的索引,而不是开头的索引。
-
- -

规范

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-sharedarraybuffer.prototype', 'SharedArrayBuffer.prototype')}}{{Spec2('ESDraft')}}Initial definition in ES2017.
- -

浏览器兼容性

- - - -

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

- -

相关链接

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/prototype/index.html deleted file mode 100644 index 00a9695a64..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/string/prototype/index.html +++ /dev/null @@ -1,187 +0,0 @@ ---- -title: String.prototype -slug: Web/JavaScript/Reference/Global_Objects/String/prototype -tags: - - JavaScript - - 原型 - - 参考 - - 字符串 - - 属性 -translation_of: Web/JavaScript/Reference/Global_Objects/String -translation_of_original: Web/JavaScript/Reference/Global_Objects/String/prototype ---- -
{{JSRef}}
- -

 String.prototype 属性表示 {{jsxref("String")}}原型对象。

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

描述

- -

所有 {{jsxref("String")}} 的实例都继承自 String.prototype. 任何String.prototype上的改变都会影响到所有的 {{jsxref("String")}} 实例。

- -

属性

- -
-
String.prototype.constructor
-
用于创造对象的原型对象的特定的函数。
-
{{jsxref("String.prototype.length")}}
-
返回了字符串的长度。
-
N
-
用于访问第N个位置的字符,其中N是小于 {{jsxref("String.length", "length")}} 和 0之间的正整数。这些属性都是“只读”性质,不能编辑。
-
- -

方法

- -

跟HTML无关的方法

- -
-
{{jsxref("String.prototype.charAt()")}}
-
返回特定位置的字符。
-
{{jsxref("String.prototype.charCodeAt()")}}
-
返回表示给定索引的字符的Unicode的值。
-
{{jsxref("String.prototype.codePointAt()")}}
-
返回使用UTF-16编码的给定位置的值的非负整数。
-
{{jsxref("String.prototype.concat()")}}
-
连接两个字符串文本,并返回一个新的字符串。
-
{{jsxref("String.prototype.includes()")}}
-
判断一个字符串里是否包含其他字符串。
-
{{jsxref("String.prototype.endsWith()")}}
-
判断一个字符串的是否以给定字符串结尾,结果返回布尔值。
-
{{jsxref("String.prototype.indexOf()")}}
-
从字符串对象中返回首个被发现的给定值的索引值,如果没有找到则返回-1。
-
{{jsxref("String.prototype.lastIndexOf()")}}
-
从字符串对象中返回最后一个被发现的给定值的索引值,如果没有找到则返回-1。
-
{{jsxref("String.prototype.localeCompare()")}}
-
返回一个数字表示是否引用字符串在排序中位于比较字符串的前面,后面,或者二者相同。
-
{{jsxref("String.prototype.match()")}}
-
使用正则表达式与字符串相比较。
-
{{jsxref("String.prototype.normalize()")}}
-
返回调用字符串值的Unicode标准化形式。
-
{{jsxref("String.prototype.padEnd()")}}
-
在当前字符串尾部填充指定的字符串, 直到达到指定的长度。 返回一个新的字符串。
-
{{jsxref("String.prototype.padStart()")}}
-
-

在当前字符串头部填充指定的字符串, 直到达到指定的长度。 返回一个新的字符串。

-
-
{{jsxref("String.prototype.quote()")}} {{ obsolete_inline }}
-
设置嵌入引用的引号类型。
-
{{jsxref("String.prototype.repeat()")}}
-
返回指定重复次数的由元素组成的字符串对象。
-
{{jsxref("String.prototype.replace()")}}
-
被用来在正则表达式和字符串直接比较,然后用新的子串来替换被匹配的子串。
-
{{jsxref("String.prototype.search()")}}
-
对正则表达式和指定字符串进行匹配搜索,返回第一个出现的匹配项的下标。
-
{{jsxref("String.prototype.slice()")}}
-
摘取一个字符串区域,返回一个新的字符串。
-
{{jsxref("String.prototype.split()")}}
-
通过分离字符串成字串,将字符串对象分割成字符串数组。
-
{{jsxref("String.prototype.startsWith()")}}
-
判断字符串的起始位置是否匹配其他字符串中的字符。
-
{{jsxref("String.prototype.substr()")}}
-
通过指定字符数返回在指定位置开始的字符串中的字符。
-
{{jsxref("String.prototype.substring()")}}
-
返回在字符串中指定两个下标之间的字符。
-
{{jsxref("String.prototype.toLocaleLowerCase()")}}
-
根据当前区域设置,将符串中的字符转换成小写。对于大多数语言来说,{{jsxref("String.toLowerCase", "toLowerCase")}}的返回值是一致的。
-
{{jsxref("String.prototype.toLocaleUpperCase()")}}
-
根据当前区域设置,将字符串中的字符转换成大写,对于大多数语言来说,{{jsxref("String.toUpperCase", "toUpperCase")}}的返回值是一致的。
-
{{jsxref("String.prototype.toLowerCase()")}}
-
将字符串转换成小写并返回。
-
{{jsxref("String.prototype.toSource()")}} {{ Non-standard_inline() }}
-
返回一个对象文字代表着特定的对象。你可以使用这个返回值来创建新的对象。重写 {{jsxref("Object.prototype.toSource")}} 方法。
-
{{jsxref("String.prototype.toString()")}}
-
返回用字符串表示的特定对象。重写 {{jsxref("Object.prototype.toString")}} 方法。
-
{{jsxref("String.prototype.toUpperCase()")}}
-
将字符串转换成大写并返回。
-
{{jsxref("String.prototype.trim()")}}
-
从字符串的开始和结尾去除空格。参照部分 ECMAScript 5 标准。
-
{{jsxref("String.prototype.trimStart()")}}
-
{{jsxref("String.prototype.trimLeft()")}} {{ Non-standard_inline() }}
-
从字符串的左侧去除空格。
-
{{jsxref("String.prototype.trimEnd()")}}
-
{{jsxref("String.prototype.trimRight()")}} {{ Non-standard_inline() }}
-
从字符串的右侧去除空格。
-
{{jsxref("String.prototype.valueOf()")}}
-
返回特定对象的原始值。重写 {{jsxref("Object.prototype.valueOf")}} 方法。
-
{{jsxref("String.prototype.@@iterator()", "String.prototype[@@iterator]()")}}
-
返回一个新的迭代器对象,该对象遍历字符串值的索引位置,将每个索引值作为字符串值返回。
-
- -

HTML wrapper methods

- -

下面的方法被限制使用,因为只对可用的HTML标签和属性提供部分支持。

- -
-
{{jsxref("String.prototype.anchor()")}}
-
<a name="name"> (hypertext target)
-
{{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}}
-
<font color="color">
-
{{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}
-
<font size="size">
-
{{jsxref("String.prototype.italics()")}} {{deprecated_inline}}
-
{{HTMLElement("i")}}
-
{{jsxref("String.prototype.link()")}}
-
<a href="url"> (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

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
规范状态备注
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')}}
{{SpecName('ESDraft', '#sec-string.prototype', 'String.prototype')}}{{Spec2('ESDraft')}}
- -

浏览器兼容性

- - - -

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

- -

更多

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/trimend/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/trimend/index.html new file mode 100644 index 0000000000..9c8319cb29 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/trimend/index.html @@ -0,0 +1,84 @@ +--- +title: String.prototype.trimRight() +slug: Web/JavaScript/Reference/Global_Objects/String/TrimRight +tags: + - JavaScript + - Method + - Prototype + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/trimEnd +--- +
{{JSRef}}
+ +

trimEnd() 方法从一个字符串的末端移除空白字符。trimRight() 是这个方法的别名。

+ +

{{EmbedInteractiveExample("pages/js/string-trimend.html")}}

+ +

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

+ +

语法

+ +
str.trimEnd();
+str.trimRight();
+ +

返回值

+ +

一个新字符串,表示从调用字串的末(右)端除去空白。

+ +

描述

+ +

trimEnd() / trimRight()方法移除原字符串右端的连续空白符并返回,trimEnd() / trimRight()方法并不会直接修改原字符串本身。

+ +

别名

+ +

为了与 {{jsxref("String.prototype.padEnd")}} 等函数保持一致,标准方法名称为trimEnd。 但是,出于Web兼容性原因,trimRight仍然是trimEnd的别名。 在某些引擎中,这意味着:

+ +
String.prototype.trimRight.name === "trimEnd";
+
+ +

示例

+ +

使用trimEnd()

+ +

下面的例子输出了小写的字符串"   foo":

+ +
var str = "   foo  ";
+
+alert(str.length); // 8
+
+str = str.trimRight();  // 或写成str = str.trimEnd();
+console.log(str.length); // 6
+console.log(str);       // '   foo'
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
String.prototype.{trimStart,trimEnd}proposalStage 4Expected to be part of ES2019
+ +

Browser compatibility

+ +

The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

+ +

{{Compat("javascript.builtins.String.trimEnd")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/trimleft/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/trimleft/index.html deleted file mode 100644 index bc6133cecb..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/string/trimleft/index.html +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: String.prototype.trimStart() -slug: Web/JavaScript/Reference/Global_Objects/String/TrimLeft -tags: - - JavaScript - - Method - - Prototype - - String - - 参考 - - 字符串 - - 方法 -translation_of: Web/JavaScript/Reference/Global_Objects/String/trimStart ---- -
{{JSRef}}
- -
trimStart() 方法从字符串的开头删除空格。trimLeft() 是此方法的别名。
- -
{{EmbedInteractiveExample("pages/js/string-trimstart.html")}}
- - - -

语法

- -
str.trimStart();
-str.trimLeft();
- -

返回值

- -

一个新字符串,表示从其开头(左端)除去空格的调用字符串。

- -

描述

- -

trimStart() / trimLeft() 方法移除原字符串左端的连续空白符并返回一个新字符串,并不会直接修改原字符串本身。

- -

别名

- -

为了与 {{jsxref("String.prototype.padStart")}} 等函数保持一致,标准方法名称为trimStart。 但是,出于 Web 兼容性原因,trimLeft 仍然是 trimStart 的别名。在某些引擎中,这意味着:

- -
String.prototype.trimLeft.name === "trimStart";
- -

示例

- -

使用 trimStart()

- -

下面的例子输出了小写的字符串 "foo  "

- -
var str = "   foo  ";
-
-console.log(str.length); // 8
-
-str = str.trimStart()    // 等同于 str = str.trimLeft();
-console.log(str.length); // 5
-console.log(str);        // "foo  "
-
- -

规范

- - - - - - - - - - - - - - - - -
规范状态备注
String.prototype.{trimStart,trimEnd}proposalStage 4Expected to be part of ES2019
- -

浏览器兼容性

- - - -

{{Compat("javascript.builtins.String.trimStart")}}

- -

Polyfill

- -
// https://github.com/FabioVergani/js-Polyfill_String-trimStart
-
-(function(w){
-    var String=w.String, Proto=String.prototype;
-
-    (function(o,p){
-        if(p in o?o[p]?false:true:true){
-            var r=/^\s+/;
-            o[p]=o.trimLeft||function(){
-                return this.replace(r,'')
-            }
-        }
-    })(Proto,'trimStart');
-
-})(window);
-
-
-/*
-ES6:
-(w=>{
-    const String=w.String, Proto=String.prototype;
-
-    ((o,p)=>{
-        if(p in o?o[p]?false:true:true){
-            const r=/^\s+/;
-            o[p]=o.trimLeft||function(){
-                return this.replace(r,'')
-            }
-        }
-    })(Proto,'trimStart');
-
-})(window);
-*/
- -

参见

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/trimright/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/trimright/index.html deleted file mode 100644 index 9c8319cb29..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/string/trimright/index.html +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: String.prototype.trimRight() -slug: Web/JavaScript/Reference/Global_Objects/String/TrimRight -tags: - - JavaScript - - Method - - Prototype - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/trimEnd ---- -
{{JSRef}}
- -

trimEnd() 方法从一个字符串的末端移除空白字符。trimRight() 是这个方法的别名。

- -

{{EmbedInteractiveExample("pages/js/string-trimend.html")}}

- -

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

- -

语法

- -
str.trimEnd();
-str.trimRight();
- -

返回值

- -

一个新字符串,表示从调用字串的末(右)端除去空白。

- -

描述

- -

trimEnd() / trimRight()方法移除原字符串右端的连续空白符并返回,trimEnd() / trimRight()方法并不会直接修改原字符串本身。

- -

别名

- -

为了与 {{jsxref("String.prototype.padEnd")}} 等函数保持一致,标准方法名称为trimEnd。 但是,出于Web兼容性原因,trimRight仍然是trimEnd的别名。 在某些引擎中,这意味着:

- -
String.prototype.trimRight.name === "trimEnd";
-
- -

示例

- -

使用trimEnd()

- -

下面的例子输出了小写的字符串"   foo":

- -
var str = "   foo  ";
-
-alert(str.length); // 8
-
-str = str.trimRight();  // 或写成str = str.trimEnd();
-console.log(str.length); // 6
-console.log(str);       // '   foo'
-
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
String.prototype.{trimStart,trimEnd}proposalStage 4Expected to be part of ES2019
- -

Browser compatibility

- -

The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

- -

{{Compat("javascript.builtins.String.trimEnd")}}

- -

相关链接

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/trimstart/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/trimstart/index.html new file mode 100644 index 0000000000..bc6133cecb --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/string/trimstart/index.html @@ -0,0 +1,122 @@ +--- +title: String.prototype.trimStart() +slug: Web/JavaScript/Reference/Global_Objects/String/TrimLeft +tags: + - JavaScript + - Method + - Prototype + - String + - 参考 + - 字符串 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/String/trimStart +--- +
{{JSRef}}
+ +
trimStart() 方法从字符串的开头删除空格。trimLeft() 是此方法的别名。
+ +
{{EmbedInteractiveExample("pages/js/string-trimstart.html")}}
+ + + +

语法

+ +
str.trimStart();
+str.trimLeft();
+ +

返回值

+ +

一个新字符串,表示从其开头(左端)除去空格的调用字符串。

+ +

描述

+ +

trimStart() / trimLeft() 方法移除原字符串左端的连续空白符并返回一个新字符串,并不会直接修改原字符串本身。

+ +

别名

+ +

为了与 {{jsxref("String.prototype.padStart")}} 等函数保持一致,标准方法名称为trimStart。 但是,出于 Web 兼容性原因,trimLeft 仍然是 trimStart 的别名。在某些引擎中,这意味着:

+ +
String.prototype.trimLeft.name === "trimStart";
+ +

示例

+ +

使用 trimStart()

+ +

下面的例子输出了小写的字符串 "foo  "

+ +
var str = "   foo  ";
+
+console.log(str.length); // 8
+
+str = str.trimStart()    // 等同于 str = str.trimLeft();
+console.log(str.length); // 5
+console.log(str);        // "foo  "
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
String.prototype.{trimStart,trimEnd}proposalStage 4Expected to be part of ES2019
+ +

浏览器兼容性

+ + + +

{{Compat("javascript.builtins.String.trimStart")}}

+ +

Polyfill

+ +
// https://github.com/FabioVergani/js-Polyfill_String-trimStart
+
+(function(w){
+    var String=w.String, Proto=String.prototype;
+
+    (function(o,p){
+        if(p in o?o[p]?false:true:true){
+            var r=/^\s+/;
+            o[p]=o.trimLeft||function(){
+                return this.replace(r,'')
+            }
+        }
+    })(Proto,'trimStart');
+
+})(window);
+
+
+/*
+ES6:
+(w=>{
+    const String=w.String, Proto=String.prototype;
+
+    ((o,p)=>{
+        if(p in o?o[p]?false:true:true){
+            const r=/^\s+/;
+            o[p]=o.trimLeft||function(){
+                return this.replace(r,'')
+            }
+        }
+    })(Proto,'trimStart');
+
+})(window);
+*/
+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/global_objects/symbol/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/symbol/prototype/index.html deleted file mode 100644 index f00b37a223..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/symbol/prototype/index.html +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Symbol.prototype -slug: Web/JavaScript/Reference/Global_Objects/Symbol/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Symbol -translation_of_original: Web/JavaScript/Reference/Global_Objects/Symbol/prototype ---- -
{{JSRef}}
- -

Symbol.prototype 表示 {{jsxref("Symbol")}} 构造函数的原型。.

- -
{{EmbedInteractiveExample("pages/js/symbol-prototype.html")}}
- -

Description

- -

{{jsxref("Symbol")}} 继承自 {{jsxref("Symbol.prototype")}}. 你可以使用构造函数的原型对象来给所有Symbol实例添加属性或者方法。

- -

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

- -

Properties

- -
-
Symbol.prototype.constructor
-
返回创建实例原型的函数. 默认为 {{jsxref("Symbol")}} 函数。
-
{{jsxref("Symbol.prototype.description")}}
-
一个包含symbol描述的只读字符串。
-
- -

Methods

- -
-
{{jsxref("Symbol.prototype.toSource()")}} {{Non-standard_inline}}
-
返回包含{{jsxref("Global_Objects/Symbol", "Symbol")}} 对象源码的字符串。覆盖{{jsxref("Object.prototype.toSource()")}} 方法。
-
{{jsxref("Symbol.prototype.toString()")}}
-
返回包含Symbol描述符的字符串。 覆盖{{jsxref("Object.prototype.toString()")}} 方法。
-
{{jsxref("Symbol.prototype.valueOf()")}}
-
返回 {{jsxref("Symbol")}} 对象的初始值.。覆盖 {{jsxref("Object.prototype.valueOf()")}} 方法。
-
{{jsxref("Symbol.prototype.@@toPrimitive()", "Symbol.prototype[@@toPrimitive]")}}
-
 返回{{jsxref("Symbol")}}对象的初始值。
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-symbol.prototype', 'Symbol.prototype')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-symbol.prototype', 'Symbol.prototype')}}{{Spec2('ESDraft')}}
- -

浏览器兼容

- -

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

- -
diff --git a/files/zh-cn/web/javascript/reference/global_objects/syntaxerror/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/syntaxerror/prototype/index.html deleted file mode 100644 index 6f109510ef..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/syntaxerror/prototype/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: SyntaxError.prototype -slug: Web/JavaScript/Reference/Global_Objects/SyntaxError/prototype -tags: - - Error - - JavaScript - - Property - - Prototype - - SyntaxError -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")}} 应该提供其子什么的信息属性,但在 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')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.11.7.6', 'NativeError.prototype')}}{{Spec2('ES5.1')}}Defined as NativeError.prototype.
{{SpecName('ES6', '#sec-nativeerror.prototype', 'NativeError.prototype')}}{{Spec2('ES6')}}Defined as NativeError.prototype.
{{SpecName('ESDraft', '#sec-nativeerror.prototype', 'NativeError.prototype')}}{{Spec2('ESDraft')}}Defined as 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/zh-cn/web/javascript/reference/global_objects/typedarray/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/typedarray/prototype/index.html deleted file mode 100644 index ae9f64bf5e..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/typedarray/prototype/index.html +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: TypedArray.prototype -slug: Web/JavaScript/Reference/Global_Objects/TypedArray/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray -translation_of_original: Web/JavaScript/Reference/Global_Objects/TypedArray/prototype ---- -
{{JSRef}}
- -

TypedArray.prototype属性表示{{jsxref("TypedArray")}}构造器的原型.

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

描述

- -

{{jsxref("TypedArray")}} 实例继承自 {{jsxref("TypedArray.prototype")}}. 你可以通过该原型对象为所有的类型化数组(typed array types)实例添加属性和方法.

- -

关于继承的更多的信息请参见关于TypedArray 的描述.

- -

属性

- -
-
TypedArray.prototype.constructor
-
返回创建实例原型的构造函数.这是相应的typed array type的默认的构造函数.
-
{{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}}
-
返回在类型化数组中的元素的数量.创建时已被固化,因此是只读的.
-
- -

methods

- -
-
{{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()")}}
-
使用指定的函数测试所有元素,并创建一个包含所有通过测试的元素的新数组. 参见 {{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()")}}
-
返回一个新的包含数组索引的数组迭代器. 参见 {{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()")}}
-
接受一个函数作为累加器(accumulator),让每个值(从右到左,亦即从尾到头)缩减为一个值.(与 reduce() 的执行方向相反). 参见{{jsxref("Array.prototype.reduceRight()")}}.
-
{{jsxref("TypedArray.prototype.reverse()")}}
-
颠倒数组中元素的位置。第一个元素会成为最后一个,最后一个会成为第一个. 参见 {{jsxref("Array.prototype.reverse()")}}.
-
{{jsxref("TypedArray.prototype.set()")}}
-
读取一个指定数组中的元素保存到格式化数组中.
-
{{jsxref("TypedArray.prototype.slice()")}}
-
浅复制(shallow copy)数组的一部分到一个新的数组,并返回这个新数组. 参见 {{jsxref("Array.prototype.slice()")}}.
-
{{jsxref("TypedArray.prototype.some()")}}
-
数组中只要有一个元素满足提供的测试函数的测试就返回true,否则返回false. 参见 {{jsxref("Array.prototype.some()")}}.
-
{{jsxref("TypedArray.prototype.sort()")}}
-
对数组进行排序,并返回原数组(是改变原数组). 参见 {{jsxref("Array.prototype.sort()")}}.
-
{{jsxref("TypedArray.prototype.subarray()")}}
-
返回给定的起始和结束索引之间的元素组成的新的类型化数组.
-
{{jsxref("TypedArray.prototype.values()")}}
-
返回有数组中的元素组成的新的数组迭代对象. 参见 {{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]()")}}
-
返回一个包含数组中每个元素的新的数组迭代对象.
-
- -

规范

- - - - - - - - - - - - - - - - - - - -
规范状态备注
{{SpecName('ES6', '#sec-properties-of-the-%typedarrayprototype%-object', 'TypedArray prototype')}}{{Spec2('ES6')}}Initial definition.
{{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/zh-cn/web/javascript/reference/global_objects/typeerror/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/typeerror/prototype/index.html deleted file mode 100644 index 42abf0c422..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/typeerror/prototype/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: TypeError.prototype -slug: Web/JavaScript/Reference/Global_Objects/TypeError/prototype -tags: - - Error - - JavaScript - - TypeError - - 原型 - - 错误 -translation_of: Web/JavaScript/Reference/Global_Objects/TypeError -translation_of_original: Web/JavaScript/Reference/Global_Objects/TypeError/prototype ---- -
{{JSRef}}
- -

TypeError.prototype 属性表示 {{jsxref("TypeError")}}构造函数的原型。

- -

 

- -

描述

- -

所有{{jsxref("TypeError")}}实例都继承自TypeError.prototype。您可以使用原型向所有实例添加属性或方法

- -

 

- -

属性

- -
-
TypeError.prototype.constructor
-
声明创建实例原型 (prototype) 的方法。
-
{{jsxref("Error.prototype.message", "TypeError.prototype.message")}}
-
错误信息。虽然 ECMA-262 规范指出 {{jsxref("TypeError")}} 应该实现其自身的 message 属性,但是在 SpiderMonkey 中,该属性继承自 {{jsxref("Error.prototype.message")}}。
-
{{jsxref("Error.prototype.name", "TypeError.prototype.name")}}
-
错误名称。继承自 {{jsxref("Error")}}。
-
{{jsxref("Error.prototype.fileName", "TypeError.prototype.fileName")}}
-
引起该错误的代码所在文件的路径。继承自 {{jsxref("Error")}}。
-
{{jsxref("Error.prototype.lineNumber", "TypeError.prototype.lineNumber")}}
-
引起错误的代码所在行的行号。继承自 {{jsxref("Error")}}。
-
{{jsxref("Error.prototype.columnNumber", "TypeError.prototype.columnNumber")}}
-
引起错误的代码所在列的列号。继承自 {{jsxref("Error")}}。
-
{{jsxref("Error.prototype.stack", "TypeError.prototype.stack")}}
-
堆栈跟踪记录。 继承自 {{jsxref("Error")}}。
-
- -

方法

- -

尽管 {{jsxref("TypeError")}} 不包含任何自己的方法, 但{{jsxref("TypeError")}}的实例通过原型链继承了一些方法。

- -

 

- -

规范

- - - - - - - - - - - - - - - - - - - - - - - - -
规范状态说明
{{SpecName('ES6', '#sec-nativeerror.prototype', 'NativeError.prototype')}}{{Spec2('ES6')}} 定义为 NativeError.prototype.
{{SpecName('ES5.1', '#sec-15.11.7.6', 'NativeError.prototype')}}{{Spec2('ES5.1')}} 定义为 NativeError.prototype.
{{SpecName('ES3', '#sec-15.11.7.6', 'NativeError.prototype')}}{{Spec2('ES3')}} 初始定义
- -

浏览器兼容性

- - - -

{{Compat("javascript.builtins.TypeError")}}

- -
 
- -

相关链接

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/urierror/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/urierror/prototype/index.html deleted file mode 100644 index c5d381250a..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/urierror/prototype/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: URIError.prototype -slug: Web/JavaScript/Reference/Global_Objects/URIError/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/URIError -translation_of_original: Web/JavaScript/Reference/Global_Objects/URIError/prototype ---- -
{{JSRef}}
- -
URIError.prototype 属性表示 {{jsxref("URIError")}} 构造器的原型。
- -

描述

- -

所有的 {{jsxref("URIError")}} 实例都继承自 URIError.prototype。 可以通过原型(prototype) 给所有的实例添加属性或者方法。

- -

属性

- -
-
URIError.prototype.constructor
-
声明创建实例原型 (prototype) 的方法。
-
{{jsxref("Error.prototype.message", "URIError.prototype.message")}}
-
错误信息。虽然 ECMA-262 规范指出 {{jsxref("URIError")}} 应该提供其自己专属的 message 属性,但是在 SpiderMonkey 中,该属性继承自 {{jsxref("Error.prototype.message")}}
-
{{jsxref("Error.prototype.name", "URIError.prototype.name")}}
-
错误名称。继承自 {{jsxref("Error")}}。
-
{{jsxref("Error.prototype.fileName", "URIError.prototype.fileName")}}
-
产生该错误的代码所在文件的路径。 继承自 {{jsxref("Error")}}。
-
{{jsxref("Error.prototype.lineNumber", "URIError.prototype.lineNumber")}}
-
产生该错误的代码所在行的行号。继承自 {{jsxref("Error")}}。
-
{{jsxref("Error.prototype.columnNumber", "URIError.prototype.columnNumber")}}
-
产生该错误的代码所在列的列号。 继承自 {{jsxref("Error")}}。
-
{{jsxref("Error.prototype.stack", "URIError.prototype.stack")}}
-
堆栈记录。继承自 {{jsxref("Error")}}。
-
- -

方法

- -

虽然 {{jsxref("URIError")}} 的原型对象自身不包含任何方法,但是 {{jsxref("URIError")}} 的实例通过原型链(prototype chain)继承了一些方法。

- -

规范

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3', '#sec-15.11.7.6', 'NativeError.prototype')}}{{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.
- -

浏览器兼容性

- -
- - -

{{Compat("javascript.builtins.URIError")}}

-
- -

相关链接

- - diff --git a/files/zh-cn/web/javascript/reference/global_objects/weakmap/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/weakmap/prototype/index.html deleted file mode 100644 index 27f1ff412a..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/weakmap/prototype/index.html +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: WeakMap.prototype -slug: Web/JavaScript/Reference/Global_Objects/WeakMap/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/WeakMap -translation_of_original: Web/JavaScript/Reference/Global_Objects/WeakMap/prototype ---- -
{{JSRef}}
- -

WeakMap.prototype属性表现为 {{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
-
返回创建WeakMap实例的原型函数。 {{jsxref("WeakMap")}}函数是默认的。
-
- -

方法

- -
-
{{jsxref("WeakMap.delete", "WeakMap.prototype.delete(key)")}}
-
移除key的关联对象。执行后 WeakMap.prototype.has(key)返回false。
-
{{jsxref("WeakMap.get", "WeakMap.prototype.get(key)")}}
-
返回key关联对象, 或者 undefined(没有key关联对象时)。
-
{{jsxref("WeakMap.has", "WeakMap.prototype.has(key)")}}
-
根据是否有key关联对象返回一个Boolean值。
-
{{jsxref("WeakMap.set", "WeakMap.prototype.set(key, value)")}}
-
在WeakMap中设置一组key关联对象,返回这个 WeakMap对象。
-
{{jsxref("WeakMap.prototype.clear()")}} {{obsolete_inline}}
-
WeakMap中移除所有的 key/value 。 注意,该方法已弃用,但可以通过创建一个空的WeakMap并替换原对象来实现 (参看 {{jsxref("WeakMap")}}的后半部分)
-
- -

规范

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-weakmap.prototype', 'WeakMap.prototype')}}{{Spec2('ES6')}}Initial definition.
{{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/zh-cn/web/javascript/reference/global_objects/weakset/prototype/index.html b/files/zh-cn/web/javascript/reference/global_objects/weakset/prototype/index.html deleted file mode 100644 index 572ab1ac73..0000000000 --- a/files/zh-cn/web/javascript/reference/global_objects/weakset/prototype/index.html +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: WeakSet.prototype -slug: Web/JavaScript/Reference/Global_Objects/WeakSet/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/WeakSet -translation_of_original: Web/JavaScript/Reference/Global_Objects/WeakSet/prototype ---- -
{{JSRef("Global_Objects", "WeakSet")}}
- -

Summary

- -

The WeakSet.prototype property represents the prototype for the {{jsxref("WeakSet")}} constructor.

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

Description

- -

{{jsxref("WeakSet")}} instances inherit from {{jsxref("WeakSet.prototype")}}. You can use the constructor's prototype object to add properties or methods to all WeakSet instances.

- -

Properties

- -
-
WeakSet.prototype.constructor
-
返回构造函数即 {{jsxref("WeakSet")}} 本身.
-
- -

Methods

- -
-
{{jsxref("WeakSet.add", "WeakSet.prototype.add(value)")}}
-
 在该 WeakSet 对象中添加一个新元素 value.
-
{{jsxref("WeakSet.delete", "WeakSet.prototype.delete(value)")}}
-
该 WeakSet 对象中删除 value 这个元素, 之后 WeakSet.prototype.has(value) 方法便会返回 false.
-
{{jsxref("WeakSet.has", "WeakSet.prototype.has(value)")}}
-
返回一个布尔值,  表示给定的值 value 是否存在于这个 WeakSet 中.
-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-weakset.prototype', 'WeakSet.prototype')}}{{Spec2('ES6')}}Initial definition.
- -

Browser compatibility

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatNo() }} {{bug(792439)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatNo() }} {{bug(792439)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
-
- -

Chrome-specific notes

- - - -

See also

- - diff --git a/files/zh-cn/web/javascript/reference/operators/addition/index.html b/files/zh-cn/web/javascript/reference/operators/addition/index.html new file mode 100644 index 0000000000..6da432b4e6 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/operators/addition/index.html @@ -0,0 +1,79 @@ +--- +title: 相加运算符 (+) +slug: Web/JavaScript/Reference/Operators/相加 +translation_of: Web/JavaScript/Reference/Operators/Addition +--- +
{{jsSidebar("相加运算符")}}
+ +

相加运算符 (+) 用于对两个操作数进行相加运算,如果操作数为字符串则该运算符将两个操作数连接成一个字符串。

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

语法

+ +
表达式: x + y
+
+ +

示例

+ +

数字的相加运算

+ +
// Number + Number -> addition
+1 + 2 // 3
+
+// Boolean + Number -> addition
+true + 1 // 2
+
+// Boolean + Boolean -> addition
+false + false // 0
+
+ +

字符串相加运算

+ +
// String + String -> concatenation
+'foo' + 'bar' // "foobar"
+
+// Number + String -> concatenation
+5 + 'foo' // "5foo"
+
+// String + Boolean -> concatenation
+'foo' + false // "foofalse"
+ +

注: '+'两侧只要有一侧是字符串,另一侧的数字则会自动转换成字符串,因为其中存在隐式转换

+ +

规范

+ + + + + + + + + + +
规范
{{SpecName('ESDraft', '#sec-addition-operator-plus', 'Addition operator')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参考

+ + diff --git a/files/zh-cn/web/javascript/reference/operators/arithmetic_operators/index.html b/files/zh-cn/web/javascript/reference/operators/arithmetic_operators/index.html deleted file mode 100644 index 917ac03b06..0000000000 --- a/files/zh-cn/web/javascript/reference/operators/arithmetic_operators/index.html +++ /dev/null @@ -1,302 +0,0 @@ ---- -title: 算术运算符 -slug: Web/JavaScript/Reference/Operators/Arithmetic_Operators -tags: - - JavaScript - - Operator -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 取模,其中 var1 和 var2 是变量。取模功能就是 var1 除以 var2 的整型余数。

- -

语法

- -
运算符: 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 ** c 等同于 a ** (b ** c)

- -

语法

- -
运算符: var1 ** var2
-
- -

注解

- -

包括 PHP 或 Python 等的大多数语言中,都包含幂运算符(一般来说符号是 ^ 或者 **)。这些语言中的幂运算符有着比其他的单目运算符(如一元 + 或一元 - )更高的优先级。但是作为例外,在 Bash 中,**  运算符被设计为比单目运算符优先级更低。在最新的 JavaScript(ES2016) 中,禁止使用带歧义的幂运算表达式。比如,底数前不能紧跟一元运算符(+/-/~/!/delete/void/typeof)。

- -
-2 ** 2;
-// 在 Bash 中等于 4 ,而在其他语言中一般等于 -4
-// 在 JavaScript 中是错误的,因为这会有歧义
-
--(2 ** 2);
-// -4 在 JavaScript 中能够明显体现出作者的意图
- -

示例

- -
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
- -

递增 (++)

- -

递增运算符为其操作数增加1,返回一个数值。

- - - -

语法

- -
运算符: x++ 或者 ++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
-
- -

一元正号 (+)

- -

一元正号运算符位于其操作数前面,计算其操作数的数值,如果操作数不是一个数值,会尝试将其转换成一个数值。 尽管一元负号也能转换非数值类型,但是一元正号是转换其他对象到数值的最快方法,也是最推荐的做法,因为它不会对数值执行任何多余操作。它可以将字符串转换成整数和浮点数形式,也可以转换非字符串值 truefalse  null。小数和十六进制格式字符串也可以转换成数值。负数形式字符串也可以转换成数值(对于十六进制不适用)。如果它不能解析一个值,则计算结果为 NaN

- -

语法

- -
运算符: +x
-
- -

示例

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

规范

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-11.3')}}{{Spec2('ES5.1')}}Defined in several sections of the specification: Additive operators, Multiplicative operators, Postfix expressions, Unary operators.
{{SpecName('ES2015', '#sec-postfix-expressions')}}{{Spec2('ES2015')}}Defined in several sections of the specification: Additive operators, Multiplicative operators, Postfix expressions, Unary operators.
{{SpecName('ES2016', '#sec-postfix-expressions')}}{{Spec2('ES2016')}}Added Exponentiation operator.
{{SpecName('ES2017', '#sec-postfix-expressions')}}{{Spec2('ES2017')}}
{{SpecName('ESDraft', '#sec-additive-operators')}}{{Spec2('ESDraft')}}
- -

浏览器兼容性

- - - -

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

- -

相关链接

- - diff --git a/files/zh-cn/web/javascript/reference/operators/assignment_operators/index.html b/files/zh-cn/web/javascript/reference/operators/assignment_operators/index.html deleted file mode 100644 index 66ae471cde..0000000000 --- a/files/zh-cn/web/javascript/reference/operators/assignment_operators/index.html +++ /dev/null @@ -1,413 +0,0 @@ ---- -title: 赋值运算符 -slug: Web/JavaScript/Reference/Operators/Assignment_Operators -tags: - - JavaScript - - 运算符 -translation_of: Web/JavaScript/Reference/Operators#Assignment_operators -translation_of_original: Web/JavaScript/Reference/Operators/Assignment_Operators ---- -
{{jsSidebar("Operators")}}
- -

赋值运算符(assignment operator)基于右值(right operand)的值,给左值(left operand)赋值。

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

概述

- -

基本的赋值运算符是等号(=),该运算符把它右边的运算值赋给左边。即,x = y 把 y 的值赋给 x。 其他的赋值运算符通常是标准运算符的简写形式,如下面的定义与示例。 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
名称简写形式含义
赋值(Assignment)x = yx = y
加赋值(Addition assignment)x += yx = x + y
减赋值(Subtraction assignment)x -= yx = x - y
乘赋值(Multiplication assigment)x *= yx = x * y
除赋值(Division assignment)x /= yx = x / y
模赋值(Remainder assignment)x %= yx = x % y
指数赋值(Exponentiation assignment)x **= yx = x ** y
左移赋值(Left shift assignment)x <<= yx = x << y
右移赋值(Right shift assignment)x >>= yx = x >> y
无符号右移赋值(Unsigned right shift assignment)x >>>= yx = x >>> y
按位与赋值(Bitwise AND assignment)x &= yx = x & y
按位异或赋值(Bitwise XOR assignment)x ^= yx = x ^ y
按位或赋值(Bitwise OR assignment)x |= yx = x | y
- -

赋值

- -

简单的赋值运算符,把一个值赋给一个变量。为了把一个值赋给多个变量,可以以链式使用赋值运算符。参考下例:

- -

语法

- -
Operator: x = y
-
- -

示例

- -
// Assuming the following variables
-//  x = 5
-//  y = 10
-//  z = 25
-
-x = y     // x is 10
-x = y = z // x, y and z are all 25
-
- -

加赋值(Addition assignment)

- -

加赋值运算符把一个右值与一个变量相加,然后把相加的结果赋给该变量。两个操作数的类型决定了加赋值运算符的行为。算术相加或字符串连接都有可能。更多细节参考 {{jsxref("Operators/Arithmetic_Operators", "addition operator", "#Addition", 1)}}。

- -

语法

- -
Operator: x += y
-Meaning:  x  = x + y
-
- -

示例

- -
// 定义下列变量
-//  foo = 'foo'
-//  bar = 5
-//  baz = true
-
-
-// Number + Number -> addition
-bar += 2 // 7
-
-// Boolean + Number -> addition
-baz += 1 // 2
-
-// Boolean + Boolean -> addition
-baz += false // 1
-
-// Number + String -> concatenation
-bar += 'foo' // "5foo"
-
-// String + Boolean -> concatenation
-foo += false // "foofalse"
-
-// String + String -> concatenation
-foo += 'bar' // "foobar"
-
- -

减赋值(Subtraction assignment)

- -

减赋值运算符使一个变量减去右值,然后把结果赋给该变量。更多细节查看 {{jsxref("Operators/Arithmetic_Operators", "subtraction operator", "#Subtraction", 1)}} 。

- -

语法

- -
Operator: x -= y
-Meaning:  x  = x - y
-
- -

示例

- -
// 假定已定义了下面的变量
-//  bar = 5
-
-bar -= 2     // 3
-bar -= "foo" // NaN
-
- -

乘赋值(Multiplication assignment)

- -

乘赋值运算符使一个变量乘以右值,然后把相成的结果赋给该变量。更多细节查看 {{jsxref("Operators/Arithmetic_Operators", "multiplication operator", "#Multiplication", 1)}}。

- -

语法

- -
Operator: x *= y
-Meaning:  x  = x * y
-
- -

示例

- -
// 假定已定义了下面的变量
-//  bar = 5
-
-bar *= 2     // 10
-bar *= 'foo' // NaN
-
- -

除赋值(Division assignment)

- -

除赋值运算符使一个变量除以右值,然后把结果赋给该变量。更多细节查看 {{jsxref("Operators/Arithmetic_Operators", "division operator", "#Division", 1)}}。

- -

语法

- -
Operator: x /= y
-Meaning:  x  = x / y
-
- -

示例

- -
// 假定已定义了下面的变量
-//  bar = 5
-
-bar /= 2     // 2.5
-bar /= "foo" // NaN
-bar /= 0     // Infinity
-
- -

模赋值(Remainder assignment)

- -

模赋值运算符使一个变量除以右值,然后把余数赋给该变量。更多细节查看 {{jsxref("Operators/Arithmetic_Operators", "remainder operator", "#Remainder", 1)}}。

- -

语法

- -
Operator: x %= y
-Meaning:  x  = x % y
-
- -

示例

- -
// Assuming the following variable
-//  bar = 5
-
-bar %= 2     // 1
-bar %= 'foo' // NaN
-bar %= 0     // NaN
-
- -

指数赋值(Exponentiation assignment)

- -

指数赋值运算符使一个变量为底数、以右值为指数的指数运算(乘方)结果赋给该变量。更多细节查看 {{jsxref("Operators/Arithmetic_Operators", "算术运算符", "#Exponentiation", 1)}}。

- -

语法

- -
语法: x **= y
-含义:  x  = x ** y
-
- -

示例

- -
// Assuming the following variable
-//  bar = 5
-
-bar **= 2     // 25
-bar **= 'foo' // NaN
- -

左移赋值(Left shift assignment)

- -

左移赋值运算符使变量向左移动指定位数的比特位,然后把结果赋给该变量。更多细节查看 {{jsxref("Operators/Bitwise_Operators", "left shift operator", "#Left_shift", 1)}}。

- -

语法

- -
Operator: x <<= y
-Meaning:  x   = x << y
-
- -

示例

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

右移赋值(Right shift assignment)

- -

右移赋值运算符使变量向右移指定位数的比特位,然后把结果赋给该变量。更多细节查看 {{jsxref("Operators/Bitwise_Operators", "right shift operator", "#Right_shift", 1)}}。

- -

语法

- -
Operator: x >>= y
-Meaning:  x   = x >> y
-
- -

示例

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

无符号右移赋值(Unsigned right shift assignment)

- -

无符号右移赋值运算符向右移动指定数量的比特位,然后把结果赋给变量。更多细节查看 {{jsxref("Operators/Bitwise_Operators", " unsigned right shift operator", "#Unsigned_right_shift", 1)}}。

- -

语法

- -
Operator: x >>>= y
-Meaning:  x    = x >>> y
-
- -

示例

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

按位与赋值(Bitwise AND assignment)

- -

按位与赋值运算符使用两个操作值的二进制表示,执行按位与运算,并把结果赋给变量。更多细节查看 {{jsxref("Operators/Bitwise_Operators", "bitwise AND operator", "#Bitwise_AND", 1)}}。

- -

语法

- -
Operator: x &= y
-Meaning:  x  = x & y
-
- -

示例

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

按位异或赋值(Bitwise XOR assignment)

- -

按位异或赋值运算符使用两个操作值的二进制表示,执行二进制异或运算,并把结果赋给变量。更多细节查看 {{jsxref("Operators/Bitwise_Operators", "bitwise XOR operator", "#Bitwise_XOR", 1)}}。

- -

语法

- -
Operator: x ^= y
-Meaning:  x  = x ^ y
-
- -

示例

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

按位或赋值(Bitwise OR assignment)

- -

按位或赋值运算符使用两个操作值的二进制表示,执行按位或运算,并把结果赋给变量。更多细节查看 {{jsxref("Operators/Bitwise_Operators", "bitwise OR operator", "#Bitwise_OR", 1)}}。

- -

语法

- -
Operator: x |= y
-Meaning:  x  = x | y
-
- -

示例

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

示例

- -

带有赋值运算符的左值(Left operand)

- -

在某些不常见的情况下,赋值运算符(如 x += y)并不等同于表达式( x = x + y)。当一个赋值运算符的左值包含有一个赋值运算符时,左值只会被求值一次。例如:

- -
a[i++] += 5         // i 执行一次求值
-a[i++] = a[i++] + 5 // i 执行两次求值
-
- -

规范

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-assignment-operators', 'Assignment operators')}}{{Spec2('ES2015')}}
{{SpecName('ES5.1', '#sec-11.13', 'Assignment operators')}}{{Spec2('ES5.1')}}
{{SpecName('ES1', '#sec-11.13', 'Assignment operators')}}{{Spec2('ES1')}}Initial definition.
- -

浏览器兼容性

- - - -

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

- -

相关链接

- - diff --git a/files/zh-cn/web/javascript/reference/operators/async_function/index.html b/files/zh-cn/web/javascript/reference/operators/async_function/index.html new file mode 100644 index 0000000000..eebfd13ca2 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/operators/async_function/index.html @@ -0,0 +1,98 @@ +--- +title: async function expression +slug: Web/JavaScript/Reference/Operators/async允许声明一个函数为一个包含异步操作的函数 +tags: + - JavaScript + - 函数 + - 基本表达式 + - 实验性内容 + - 操作符 +translation_of: Web/JavaScript/Reference/Operators/async_function +--- +
{{jsSidebar("Operators")}}
+ +
 
+ +

async function 关键字用来在表达式中定义异步函数。当然,你也可以用 {{jsxref('Statements/async_function', '异步函数语句')}} 来定义。

+ +

语法

+ +
async function [name]([param1[, param2[, ..., paramN]]]) { statements }
+ +

参数

+ +
+
name
+
此异步函数的名称,可省略。如果省略则这个函数将成为匿名函数。该名称仅可在本函数中使用。
+
paramN
+
传入函数的形参名称。
+
statements
+
组成函数体的语句。
+
+ +

描述

+ +

异步函数表达式与 {{jsxref('Statements/async_function', '异步函数语句')}} 非常相似,语法也基本相同。它们之间的主要区别在于异步函数表达式可以省略函数名称来创建一个匿名函数。另外,异步函数表达式还可以用在 {{Glossary("IIFE")}} (立即执行函数表达式,Immediately Invoked Function Expression) 中,更多信息见 {{jsxref('Reference/Functions', '函数')}}。

+ +

示例

+ +

一个简单例子

+ +
function resolveAfter2Seconds(x) {
+  return new Promise(resolve => {
+    setTimeout(() => {
+      resolve(x);
+    }, 2000);
+  });
+};
+
+// async function expression assigned to a variable
+var add1 = async function(x) {
+  var a = await resolveAfter2Seconds(20);
+  var b = await resolveAfter2Seconds(30);
+  return x + a + b;
+}
+
+add1(10).then(v => {
+  console.log(v);  // 4 秒后打印 60
+});
+
+(async function(x) { // async function expression used as an IIFE
+  var p_a = resolveAfter2Seconds(20);
+  var p_b = resolveAfter2Seconds(30);
+  return x + await p_a + await p_b;
+})(10).then(v => {
+  console.log(v);  // 2 秒后打印 60
+});
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}{{Spec2('ESDraft')}}ES2017 中的初始定义
+ +

浏览器兼容性

+ +
{{Compat("javascript.operators.async_function_expression")}}
+ +

相关链接

+ + diff --git "a/files/zh-cn/web/javascript/reference/operators/async\345\205\201\350\256\270\345\243\260\346\230\216\344\270\200\344\270\252\345\207\275\346\225\260\344\270\272\344\270\200\344\270\252\345\214\205\345\220\253\345\274\202\346\255\245\346\223\215\344\275\234\347\232\204\345\207\275\346\225\260/index.html" "b/files/zh-cn/web/javascript/reference/operators/async\345\205\201\350\256\270\345\243\260\346\230\216\344\270\200\344\270\252\345\207\275\346\225\260\344\270\272\344\270\200\344\270\252\345\214\205\345\220\253\345\274\202\346\255\245\346\223\215\344\275\234\347\232\204\345\207\275\346\225\260/index.html" deleted file mode 100644 index eebfd13ca2..0000000000 --- "a/files/zh-cn/web/javascript/reference/operators/async\345\205\201\350\256\270\345\243\260\346\230\216\344\270\200\344\270\252\345\207\275\346\225\260\344\270\272\344\270\200\344\270\252\345\214\205\345\220\253\345\274\202\346\255\245\346\223\215\344\275\234\347\232\204\345\207\275\346\225\260/index.html" +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: async function expression -slug: Web/JavaScript/Reference/Operators/async允许声明一个函数为一个包含异步操作的函数 -tags: - - JavaScript - - 函数 - - 基本表达式 - - 实验性内容 - - 操作符 -translation_of: Web/JavaScript/Reference/Operators/async_function ---- -
{{jsSidebar("Operators")}}
- -
 
- -

async function 关键字用来在表达式中定义异步函数。当然,你也可以用 {{jsxref('Statements/async_function', '异步函数语句')}} 来定义。

- -

语法

- -
async function [name]([param1[, param2[, ..., paramN]]]) { statements }
- -

参数

- -
-
name
-
此异步函数的名称,可省略。如果省略则这个函数将成为匿名函数。该名称仅可在本函数中使用。
-
paramN
-
传入函数的形参名称。
-
statements
-
组成函数体的语句。
-
- -

描述

- -

异步函数表达式与 {{jsxref('Statements/async_function', '异步函数语句')}} 非常相似,语法也基本相同。它们之间的主要区别在于异步函数表达式可以省略函数名称来创建一个匿名函数。另外,异步函数表达式还可以用在 {{Glossary("IIFE")}} (立即执行函数表达式,Immediately Invoked Function Expression) 中,更多信息见 {{jsxref('Reference/Functions', '函数')}}。

- -

示例

- -

一个简单例子

- -
function resolveAfter2Seconds(x) {
-  return new Promise(resolve => {
-    setTimeout(() => {
-      resolve(x);
-    }, 2000);
-  });
-};
-
-// async function expression assigned to a variable
-var add1 = async function(x) {
-  var a = await resolveAfter2Seconds(20);
-  var b = await resolveAfter2Seconds(30);
-  return x + a + b;
-}
-
-add1(10).then(v => {
-  console.log(v);  // 4 秒后打印 60
-});
-
-(async function(x) { // async function expression used as an IIFE
-  var p_a = resolveAfter2Seconds(20);
-  var p_b = resolveAfter2Seconds(30);
-  return x + await p_a + await p_b;
-})(10).then(v => {
-  console.log(v);  // 2 秒后打印 60
-});
-
- -

规范

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}{{Spec2('ESDraft')}}ES2017 中的初始定义
- -

浏览器兼容性

- -
{{Compat("javascript.operators.async_function_expression")}}
- -

相关链接

- - diff --git a/files/zh-cn/web/javascript/reference/operators/bitwise_and/index.html b/files/zh-cn/web/javascript/reference/operators/bitwise_and/index.html new file mode 100644 index 0000000000..20eece2691 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/operators/bitwise_and/index.html @@ -0,0 +1,106 @@ +--- +title: 按位与 (&) +slug: Web/JavaScript/Reference/Operators/按位与 +translation_of: Web/JavaScript/Reference/Operators/Bitwise_AND +--- +
{{jsSidebar("Operators")}}
+ +

按位与运算符 (&) 在每个位上返回 1 ,这两个操作数对应的位都是 1.

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

语法

+ +
a & b
+
+ +

描述

+ +

操作数被转换为32位整数,并由一系列位(0和1)表示。 超过32位的数字将丢弃其最高有效位。 例如,以下大于32位的整数将被转换为32位整数:

+ +
Before: 11100110111110100000000000000110000000000001
+After:              10100000000000000110000000000001
+ +

第一个操作数中的每个位都与第二个操作数中的相应位配对:第一位到第一位,第二位到第二位,依此类推。

+ +

将运算符应用于每对位,然后按位构造结果。

+ +

与运算的真值表:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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)
+
+ +

将任何数字x0进行按位与运算将得出0

+ +

示例

+ +

使用按位与

+ +
// 5: 00000000000000000000000000000101
+// 2: 00000000000000000000000000000010
+5 & 2; // 0
+ +

规范说明

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#prod-BitwiseANDExpression', 'Bitwise AND expression')}}
+ +

浏览器兼容性

+ + + +

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

+ +

参阅

+ + diff --git a/files/zh-cn/web/javascript/reference/operators/bitwise_operators/index.html b/files/zh-cn/web/javascript/reference/operators/bitwise_operators/index.html deleted file mode 100644 index 4bdd7a1bc7..0000000000 --- a/files/zh-cn/web/javascript/reference/operators/bitwise_operators/index.html +++ /dev/null @@ -1,756 +0,0 @@ ---- -title: 按位操作符 -slug: Web/JavaScript/Reference/Operators/Bitwise_Operators -tags: - - js ^ & Bitwise Operators -translation_of: Web/JavaScript/Reference/Operators -translation_of_original: Web/JavaScript/Reference/Operators/Bitwise_Operators ---- -
{{jsSidebar("Operators")}}
- -

概述

- -

按位操作符(Bitwise operators) 将其操作数(operands)当作32位的比特序列(由0和1组成),而不是十进制、十六进制或八进制数值。例如,十进制数9,用二进制表示则为1001。按位操作符操作数字的二进制形式,但是返回值依然是标准的JavaScript数值。

- -

下面的表格总结了JavaScript中的按位操作符:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
运算符用法描述
按位与( AND)a & b对于每一个比特位,只有两个操作数相应的比特位都是1时,结果才为1,否则为0。
按位或(OR)a | b对于每一个比特位,当两个操作数相应的比特位至少有一个1时,结果为1,否则为0。
按位异或(XOR)a ^ b对于每一个比特位,当两个操作数相应的比特位有且只有一个1时,结果为1,否则为0。
按位非(NOT)~ a反转操作数的比特位,即0变成1,1变成0。
左移(Left shift)a << b将 a 的二进制形式向左移 b (< 32) 比特位,右边用0填充。
有符号右移a >> b将 a 的二进制表示向右移 b (< 32) 位,丢弃被移出的位。
无符号右移a >>> b将 a 的二进制表示向右移 b (< 32) 位,丢弃被移出的位,并使用 0 在左侧填充。
- -

有符号32位整数

- -

所有的按位操作符的操作数都会被转成补码(two's complement)形式的有符号32位整数。补码形式是指一个数的负对应值(negative counterpart)(如 5和-5)为数值的所有比特位反转后,再加1。反转比特位即该数值进行’非‘位运算,也即该数值的反码。例如下面为整数314的二进制编码:

- -
00000000000000000000000100111010
-
- -

下面编码 ~314,即 314 的反码:

- -
11111111111111111111111011000101
-
- -

最后,下面编码 -314,即 314 的反码再加1:

- -
11111111111111111111111011000110
-
- -

补码保证了当一个数是正数时,其最左的比特位是0,当一个数是负数时,其最左的比特位是1。因此,最左边的比特位被称为符号位(sign bit)。

- -

0 是所有比特数字0组成的整数。

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

-1 是所有比特数字1组成的整数。

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

-2147483648(十六进制形式:-0x80000000)是除了最左边为1外,其他比特位都为0的整数。

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

2147483647(十六进制形式:0x7fffffff)是除了最左边为0外,其他比特位都为1的整数。

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

数字-21474836482147483647 是32位有符号数字所能表示的最小和最大整数。

- -

按位逻辑操作符

- -

从概念上讲,按位逻辑操作符按遵守下面规则:

- - - -

& (按位与)

- -

对每对比特位执行与(AND)操作。只有 a 和 b 都是 1 时,a AND b 才是 1。与操作的真值表如下:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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)
-
- -

将任一数值 x 与 0 执行按位与操作,其结果都为 0。将任一数值 x 与 -1 执行按位与操作,其结果都为 x。

- -

| (按位或)

- -

对每一对比特位执行或(OR)操作。如果 a 或 b 为 1,则 a OR b 结果为 1。或操作的真值表:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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)
-
- -

将任一数值 x 与 0 进行按位或操作,其结果都是 x。将任一数值 x 与 -1 进行按位或操作,其结果都为 -1。

- -

补充一些例子:

- -
1 | 0 ;                       // 1
-
-1.1 | 0 ;                     // 1
-
-'asfdasfda' | 0 ;             // 0
-
-0 | 0 ;                       // 0
-
-(-1) | 0 ;                    // -1
-
-(-1.5646) | 0 ;               // -1
-
-[] | 0 ;                      // 0
-
-({}) | 0 ;                    // 0
-
-"123456" | 0 ;            // 123456
-
-1.23E2 | 0;               // 123
-
-1.23E12 | 0;              // 1639353344
-
--1.23E2 | 0;              // -123
-
--1.23E12 | 0;             // -1639353344
- -

^ (按位异或)

- -

对每一对比特位执行异或(XOR)操作。当 a 和 b 不相同时,a XOR b 的结果为 1。异或操作真值表:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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)
-
- -

将任一数值 x 与 0 进行异或操作,其结果为 x。将任一数值 x 与 -1 进行异或操作,其结果为 ~x。

- -

~ (按位非)

- -

对每一个比特位执行非(NOT)操作。NOT a 结果为 a 的反转(即反码)。非操作的真值表:

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

对任一数值 x 进行按位非操作的结果为 -(x + 1)。例如,~5 结果为 -6。

- -

与 indexOf 一起使用示例:

- -
var str = 'rawr';
-var searchFor = 'a';
-
-// 这是 if (-1*str.indexOf('a') <= 0) 条件判断的另一种方法
-if (~str.indexOf(searchFor)) {
-  // searchFor 包含在字符串中
-} else {
-  // searchFor 不包含在字符串中
-}
-
-// (~str.indexOf(searchFor))的返回值
-// r == -1
-// a == -2
-// w == -3
-
- -

按位移动操作符

- -

按位移动操作符有两个操作数:第一个是要被移动的数字,而第二个是要移动的长度。移动的方向根据操作符的不同而不同。

- -

按位移动会先将操作数转换为大端字节序顺序(big-endian order)的32位整数,并返回与左操作数相同类型的结果。右操作数应小于 32位,否则只有最低 5 个字节会被使用。

- -
注:Big-Endian:高位字节排放在内存的低地址端,低位字节排放在内存的高地址端,
-又称为"高位编址"。
-Big-Endian是最直观的字节序:
-①把内存地址从左到右按照由低到高的顺序写出;
-②把值按照通常的高位到低位的顺序写出;
-③两者对照,一个字节一个字节的填充进去。
- -

<< (左移)

- -

该操作符会将第一个操作数向左移动指定的位数。向左被移出的位被丢弃,右侧用 0 补充。

- -

For example, 9 << 2 yields 36:

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

在数字 x 上左移 y 比特得到 x * 2y.

- -

>> (有符号右移)

- -

该操作符会将第一个操作数向右移动指定的位数。向右被移出的位被丢弃,拷贝最左侧的位以填充左侧。由于新的最左侧的位总是和以前相同,符号位没有被改变。所以被称作“符号传播”。

- -

例如, 9 >> 2 得到 2:

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

相比之下, -9 >> 2 得到 -3,因为符号被保留了。

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

>>> (无符号右移)

- -

该操作符会将第一个操作数向右移动指定的位数。向右被移出的位被丢弃,左侧用0填充。因为符号位变成了 0,所以结果总是非负的。(译注:即便右移 0 个比特,结果也是非负的。)

- -

对于非负数,有符号右移和无符号右移总是返回相同的结果。例如 9 >>> 29 >> 2 一样返回 2:

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

但是对于负数却不尽相同。 -9 >>> 2 产生 1073741821 这和 -9 >> 2 不同:

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

示例

- -

例子:标志位与掩码

- -

位运算经常被用来创建、处理以及读取标志位序列——一种类似二进制的变量。虽然可以使用变量代替标志位序列,但是这样可以节省内存(1/32)。

- -

例如,有 4 个标志位:

- - - -

标志位通过位序列 DCBA 来表示。当一个位被置位 (set) 时,它的值为 1 。当被清除 (clear) 时,它的值为 0 。例如一个变量 flags 的二进制值为 0101:

- -
var flags = 5;   // 二进制 0101
-
- -

这个值表示:

- - - -

因为位运算是 32 位的, 0101 实际上是 00000000000000000000000000000101。因为前面多余的 0 没有任何意义,所以他们可以被忽略。

- -

掩码 (bitmask) 是一个通过与/或来读取标志位的位序列。典型的定义每个标志位的原语掩码如下:

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

新的掩码可以在以上掩码上使用逻辑运算创建。例如,掩码 1011 可以通过 FLAG_A、FLAG_B 和 FLAG_D 逻辑或得到:

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

某个特定的位可以通过与掩码做逻辑与运算得到,通过与掩码的与运算可以去掉无关的位,得到特定的位。例如,掩码 0100 可以用来检查标志位 C 是否被置位:

- -
// 如果我们有 cat
-if (flags & FLAG_C) { // 0101 & 0100 => 0100 => true
-   // do stuff
-}
-
- -

一个有多个位被置位的掩码表达任一/或者的含义。例如,以下两个表达是等价的:

- -
// 如果我们有 bat 或者 cat 至少一个
-// (0101 & 0010) || (0101 & 0100) => 0000 || 0100 => true
-if ((flags & FLAG_B) || (flags & FLAG_C)) {
-   // do stuff
-}
-
- -
// 如果我们有 bat 或者 cat 至少一个
-var mask = FLAG_B | FLAG_C; // 0010 | 0100 => 0110
-if (flags & mask) { // 0101 & 0110 => 0100 => true
-   // do stuff
-}
-
- -

可以通过与掩码做或运算设置标志位,掩码中为 1 的位可以设置对应的位。例如掩码 1100 可用来设置位 C 和 D:

- -
// 我们有 cat 和 duck
-var mask = FLAG_C | FLAG_D; // 0100 | 1000 => 1100
-flags |= mask;   // 0101 | 1100 => 1101
-
- -

可以通过与掩码做与运算清除标志位,掩码中为 0 的位可以设置对应的位。掩码可以通过对原语掩码做非运算得到。例如,掩码 1010 可以用来清除标志位 A 和 C :

- -
// 我们没有 ant 也没有 cat
-var mask = ~(FLAG_A | FLAG_C); // ~0101 => 1010
-flags &= mask;   // 1101 & 1010 => 1000
-
- -

如上的掩码同样可以通过 ~FLAG_A & ~FLAG_C 得到(德摩根定律):

- -
// 我们没有 ant 也没有 cat
-var mask = ~FLAG_A & ~FLAG_C;
-flags &= mask;   // 1101 & 1010 => 1000
-
- -

标志位可以使用异或运算切换。所有值为 1 的位可以切换对应的位。例如,掩码 0110 可以用来切换标志位 B 和 C:

- -
// 如果我们以前没有 bat ,那么我们现在有 bat
-// 但是如果我们已经有了一个,那么现在没有了
-// 对 cat 也是相同的情况
-var mask = FLAG_B | FLAG_C;
-flags = flags ^ mask;   // 1100 ^ 0110 => 1010
-
- -

最后,所有标志位可以通过非运算翻转:

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

转换片段

- -

将一个二进制数的 String 转换为十进制的 Number:

- -
var sBinString = "1011";
-var nMyNumber = parseInt(sBinString, 2);
-alert(nMyNumber); // 打印 11
-
- -

将一个十进制的 Number 转换为二进制数的 String:

- -
var nMyNumber = 11;
-var sBinString = nMyNumber.toString(2);
-alert(sBinString); // 打印 1011
-
- -

自动化掩码创建

- -

如果你需要从一系列的 Boolean 值创建一个掩码,你可以:

- -
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); // 打印 11
-
- -

逆算法:从掩码得到布尔数组

- -

如果你希望从掩码得到得到 Boolean Array

- -
function arrayFromMask (nMask) {
-  // nMask 必须介于 -2147483648 和 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(", ") + "]");
-// 打印 "[true, true, false, true]", i.e.: 11, i.e.: 1011
-
- -

你可以同时测试以上两个算法……

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

仅仅由于教学目的 (因为有 Number.toString(2) 方法),我们展示如何修改 arrayFromMask 算法通过 Number 返回二进制的 String,而非 Boolean Array:

- -
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);
-// 打印 00000000000000000000000000001011, i.e. 11
-
- -

规范

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-11.4.8', 'Bitwise NOT operator')}}
- {{SpecName('ES5.1', '#sec-11.7', 'Bitwise shift operators')}}
- {{SpecName('ES5.1', '#sec-11.10', 'Binary bitwise operators')}}
{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-bitwise-not-operator', 'Bitwise NOT operator')}}
- {{SpecName('ES6', '#sec-bitwise-shift-operators', 'Bitwise shift operators')}}
- {{SpecName('ES6', '#sec-binary-bitwise-operators', 'Binary bitwise operators')}}
{{Spec2('ES6')}}
- -

浏览器兼容性

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Bitwise NOT (~){{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Bitwise AND (&){{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Bitwise OR (|){{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Bitwise XOR (^){{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Left shift (<<){{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Right shift (>>){{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Unsigned right shift (>>>){{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Bitwise NOT (~){{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Bitwise AND (&){{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Bitwise OR (|){{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Bitwise XOR (^){{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Left shift (<<){{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Right shift (>>){{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Unsigned right shift (>>>){{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
-
- -

相关链接

- - diff --git a/files/zh-cn/web/javascript/reference/operators/comparison_operators/index.html b/files/zh-cn/web/javascript/reference/operators/comparison_operators/index.html deleted file mode 100644 index 5ddf85f426..0000000000 --- a/files/zh-cn/web/javascript/reference/operators/comparison_operators/index.html +++ /dev/null @@ -1,278 +0,0 @@ ---- -title: 比较操作符 -slug: Web/JavaScript/Reference/Operators/Comparison_Operators -tags: - - 严格比较操作符 - - 比较操作符 -translation_of: Web/JavaScript/Reference/Operators -translation_of_original: Web/JavaScript/Reference/Operators/Comparison_Operators ---- -
{{jsSidebar("Operators")}}
- -

JavaScript 有两种比较方式:严格比较运算符和转换类型比较运算符。对于严格比较运算符(===)来说,仅当两个操作数的类型相同且值相等为 true,而对于被广泛使用的比较运算符(==)来说,会在进行比较之前,将两个操作数转换成相同的类型。对于关系运算符(比如 <=)来说,会先将操作数转为原始值,使它们类型相同,再进行比较运算。

- -

字符串比较则是使用基于标准字典的 Unicode 值来进行比较的。

- -

比较的特点:

- - - -

相等运算符

- -

相等(==)

- -

比较操作符会为两个不同类型的操作数转换类型,然后进行严格比较。当两个操作数都是对象时,JavaScript会比较其内部引用,当且仅当他们的引用指向内存中的相同对象(区域)时才相等,即他们在栈内存中的引用地址相同。

- -

语法

- -
x == y
-
- -

例子

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

不相等 (!=)

- -

不等操作符仅当操作数不相等时返回true,如果两操作数不是同一类型,JavaScript会尝试将其转为一个合适的类型,然后进行比较。如果两操作数为对象类型,JavaScript会比较其内部引用地址,仅当他们在内存中引用不同对象时不相等。

- -

语法

- -
x != y
- -

例子

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

一致/严格相等 (===)

- -

一致运算符不会进行类型转换,仅当操作数严格相等时返回true

- -

语法

- -
x === y
- -

例子

- -
3 === 3   // true
-3 === '3' // false
-var object1 = {"value":"key"}, object2={"value":"key"};
-object1 === object2 //false
- -

不一致/严格不相等 (!==)

- -

不一致运算符当操作数不相等或不同类型时返回true

- -

语法

- -
x !== y
- -

例子

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

关系运算符

- -

大于运算符 (>)

- -

大于运算符仅当左操作数大于右操作数时返回true

- -

语法

- -
x > y
- -

例子

- -
4 > 3 // true
-
- -

大于等于运算符 (>=)

- -

大于等于运算符当左操作数大于或等于右操作数时返回true

- -

语法

- -
 x >= y
- -

例子

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

小于运算符 (<)

- -

小于运算符仅当左操作数小于右操作数时返回true

- -

语法

- -
 x < y
- -

例子

- -
3 < 4 // true
-
- -

小于等于运算符 (<=)

- -

小于等于运算符当左操作数小于或等于右操作数时返回true

- -

语法

- -
 x <= y
- -

例子

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

使用比较操作符

- -

标准相等操作符(== and !=) 使用 Abstract Equality Comparison Algorithm 去比较两个操作数。当两个操作数类型不相等时,会在比较前尝试将其转换为相同类型。 e.g., 对于表达式 5 == '5', 在比较前会先将右边字符串类型的操作数 5 转换为数字。

- -

严格相等操作符 (=== and !==) 使用 Strict Equality Comparison Algorithm 并尝试对两个相同操作数进行相等比较,如果它们的类型不相等,那么永远会返回false 所以 5 !== '5'。

- -

当需要明确操作数的类型和值的时候,或者操作数的确切类型非常重要时,应使用严格相等操作符。否则,当你允许操作数在比较前进行类型转换时,可以使用标准相等操作符来比较。

- -

当比较运算涉及类型转换时 (i.e., non–strict comparison), JavaScript 会按以下规则对字符串,数字,布尔或对象类型的操作数进行操作:

- - - -
注意: 字符串对象的类型是对象,不是字符串!字符串对象很少被使用,所以下面的结果也许会让你惊讶:
- -
// 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' 
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition. Implemented in JavaScript 1.0
ECMAScript 3rd Edition.StandardAdds === and !== operators. Implemented in JavaScript 1.3
{{SpecName('ES5.1', '#sec-11.8', 'Relational Operators')}}
- {{SpecName('ES5.1', '#sec-11.9', 'Equality Operators')}}
{{Spec2('ES5.1')}}Defined in several sections of the specification: Relational OperatorsEquality Operators
{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}
- {{SpecName('ES6', '#sec-equality-operators', 'Equality Operators')}}
{{Spec2('ES6')}}Defined in several sections of the specification: Relational OperatorsEquality Operators
{{SpecName('ESDraft', '#sec-relational-operators')}}{{Spec2('ESDraft')}}Defined in several sections of the specification: Relational OperatorsEquality Operators
- -

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/zh-cn/web/javascript/reference/operators/decrement/index.html b/files/zh-cn/web/javascript/reference/operators/decrement/index.html new file mode 100644 index 0000000000..f405740df3 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/operators/decrement/index.html @@ -0,0 +1,85 @@ +--- +title: 自减 (--) +slug: Web/JavaScript/Reference/Operators/自减 +tags: + - JavaScript + - 自减 + - 语法特性 + - 运算符 +translation_of: Web/JavaScript/Reference/Operators/Decrement +--- +
{{jsSidebar("Operators")}}
+ +

 自减运算符(--) 将它的操作数减一,然后返回操作数.

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


+ 语法

+ +
操作符: x-- or --x
+
+ +

语法细节

+ +

如果使用后缀式,即将操作符放在操作数的后面 (如,x--),运算会减一,然后返回减一之前的值。

+ +

如果使用前缀式,即将操作符放在操作数的前面 (如,--x),运算会减一,然后返回减一之后的值。

+ +

示例

+ +

后缀式

+ +
let x = 3;
+y = x--;
+
+// y = 3
+// x = 2
+
+ +

前缀式

+ +
let a = 2;
+b = --a;
+
+// a = 1
+// b = 1
+
+ +

规范

+ + + + + + + + + + +
规范
{{SpecName('ESDraft', '#sec-postfix-decrement-operator', '自减运算符')}}
+ +


+ 浏览器兼容性

+ + + +

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

+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/operators/equality/index.html b/files/zh-cn/web/javascript/reference/operators/equality/index.html new file mode 100644 index 0000000000..e100ec1d2d --- /dev/null +++ b/files/zh-cn/web/javascript/reference/operators/equality/index.html @@ -0,0 +1,125 @@ +--- +title: 相等(==) +slug: Web/JavaScript/Reference/Operators/相等 +tags: + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Operators/Equality +--- +
{{jsSidebar("Operators")}}
+ +

等于运算符(==)检查其两个操作数是否相等,并返回Boolean结果。与严格相等运算符(===)不同,它会尝试强制类型转换并且比较不同类型的操作数。

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

语法

+ +
x == y
+
+ +

描述

+ +

相等运算符(==!=)使用抽象相等比较算法比较两个操作数。可以大致概括如下:

+ + + +

此运算符与严格等于===)运算符之间最显着的区别在于,严格等于运算符不尝试类型转换。相反,严格相等运算符始终将不同类型的操作数视为不同。

+ +

例子

+ +

没有类型转换的比较

+ +
1 == 1;              // true
+"hello" == "hello";  // true
+ +

与类型转换比较

+ +
"1" ==  1;            // true
+1 == "1";             // true
+0 == false;           // true
+0 == null;            // false
+0 == undefined;       // false
+null == undefined;    // true
+
+const number1 = new Number(3);
+const number2 = new Number(3);
+number1 == 3;         // true
+number1 == number2;   // false
+ +

对象比较

+ +
const object1 = {"key": "value"}
+const object2 = {"key": "value"};
+
+object1 == object2 // false
+object2 == object2 // true
+ +

比较字符串和String对象

+ +

请注意,使用构造的字符串new String()是对象。如果将其中之一与字符串文字进行比较,则该String对象将被转换为字符串文字并对其内容进行比较。但是,如果两个操作数都是String对象,则将它们作为对象进行比较,并且必须引用相同的对象才能进行比较:

+ +
const string1 = "hello";
+const string2 = String("hello");
+const string3 = new String("hello");
+const string4 = new String("hello");
+
+console.log(string1 == string2); // true
+console.log(string1 == string3); // true
+console.log(string2 == string3); // true
+console.log(string3 == string4); // false
+console.log(string4 == string4); // true
+ +

比较日期和字符串

+ +
const d = new Date('December 17, 1995 03:24:00');
+const s = d.toString(); // for example: "Sun Dec 17 1995 03:24:00 GMT-0800 (Pacific Standard Time)"
+console.log(d == s);    //true
+ +

技术指标

+ + + + + + + + + + + + +
规范
{{SpecName('ESDraft', '#sec-equality-operators', 'Equality operators')}}
+ +

浏览器兼容性

+ +

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

+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/operators/logical_and/index.html b/files/zh-cn/web/javascript/reference/operators/logical_and/index.html new file mode 100644 index 0000000000..de38317f42 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/operators/logical_and/index.html @@ -0,0 +1,137 @@ +--- +title: 逻辑与(&&) +slug: Web/JavaScript/Reference/Operators/逻辑和 +translation_of: Web/JavaScript/Reference/Operators/Logical_AND +--- +
{{jsSidebar("Operators")}}
+ +

The logical AND (&&) operator (logical conjunction) for a set of operands is true if and only if all of its operands are true. It is typically used with {{jsxref("Boolean")}} (logical) values. When it is, it returns a Boolean value. However, the && operator actually returns the value of one of the specified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value.

+ +
{{EmbedInteractiveExample("pages/js/expressions-logical-and.html", "shorter")}}
+ + + +

Syntax

+ +
expr1 && expr2
+
+ +

Description

+ +

If expr1 can be converted to true, returns expr2; else, returns expr1.

+ +

If a value can be converted to true, the value is so-called {{Glossary("truthy")}}. If a value can be converted to false, the value is so-called {{Glossary("falsy")}}.

+ +

Examples of expressions that can be converted to false are:

+ + + +

Even though the && operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the {{jsxref("Global_Objects/Boolean/Boolean", "Boolean")}} constructor.

+ +

Short-circuit evaluation

+ +

The logical AND expression is evaluated left to right, it is tested for possible "short-circuit" evaluation using the following rule:

+ +

(some falsy expression) && expr is short-circuit evaluated to the falsy expression;

+ +

Short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). This happens because the value of the operator is already determined after the evaluation of the first operand. See example:

+ +
function A(){ console.log('called A'); return false; }
+function B(){ console.log('called B'); return true; }
+
+console.log( A() && B() );
+// logs "called A" due to the function call,
+// then logs false (which is the resulting value of the operator)
+
+ +

Operator precedence

+ +

The following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence).

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

Examples

+ +

Using AND

+ +

The following code shows examples of the && (logical AND) operator.

+ +
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
+ +

Conversion rules for booleans

+ +

Converting AND to OR

+ +

The following operation involving booleans:

+ +
bCondition1 && bCondition2
+ +

is always equal to:

+ +
!(!bCondition1 || !bCondition2)
+ +

Converting OR to AND

+ +

The following operation involving booleans:

+ +
bCondition1 || bCondition2
+ +

is always equal to:

+ +
!(!bCondition1 && !bCondition2)
+ +

Removing nested parentheses

+ +

As logical expressions are evaluated left to right, it is always possible to remove parentheses from a complex expression following some rules.

+ +

The following composite operation involving booleans:

+ +
bCondition1 || (bCondition2 && bCondition3)
+ +

is always equal to:

+ +
bCondition1 || bCondition2 && bCondition3
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#prod-LogicalANDExpression', 'Logical AND expression')}}
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-cn/web/javascript/reference/operators/logical_operators/index.html b/files/zh-cn/web/javascript/reference/operators/logical_operators/index.html deleted file mode 100644 index 5615e17d45..0000000000 --- a/files/zh-cn/web/javascript/reference/operators/logical_operators/index.html +++ /dev/null @@ -1,238 +0,0 @@ ---- -title: 逻辑运算符 -slug: Web/JavaScript/Reference/Operators/Logical_Operators -tags: - - JavaScript - - 操作符 - - 逻辑 -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 && expr2expr1 可转换为 true,则返回 expr2;否则,返回 expr1
逻辑或,OR(||expr1 || expr2expr1 可转换为 true,则返回 expr1;否则,返回 expr2
逻辑非,NOT(!!exprexpr 可转换为 true,则返回 false;否则,返回 true
- -

如果一个值可以被转换为 true,那么这个值就是所谓的 {{Glossary("truthy")}},如果可以被转换为 false,那么这个值就是所谓的 {{Glossary("falsy")}}。

- -

会被转换为 false 的表达式有:

- - - -

尽管 &&|| 运算符能够使用非布尔值的操作数, 但它们依然可以被看作是布尔操作符,因为它们的返回值总是能够被转换为布尔值。如果要显式地将它们的返回值(或者表达式)转换为布尔值,请使用双重非运算符(即!!)或者Boolean构造函数。

- -

短路计算

- -

由于逻辑表达式的运算顺序是从左到右,也可以用以下规则进行"短路"计算:

- - - -

短路意味着上述表达式中的expr部分不会被执行,因此expr的任何副作用都不会生效(举个例子,如果expr是一次函数调用,这次调用就不会发生)。造成这种现象的原因是,整个表达式的值在第一个操作数被计算后已经确定了。看一个例子:

- -
function A(){ console.log('called A'); return false; }
-function B(){ console.log('called B'); return true; }
-
-console.log( A() && B() );
-// logs "called A" due to the function call,
-// then logs false (which is the resulting value of the operator)
-
-console.log( B() || A() );
-// logs "called B" due to the function call,
-// then logs true (which is the resulting value of the operator)
-
- -

Operators precedence

- -

请注意,由于运算符优先级的存在,下面的表达式的结果却不相同。右侧被小括号括起来的操作变成了独立的表达式。

- -
false &&  true || true      // 结果为 true
-false && (true || true)     // 结果为 false
-
- -

逻辑与(&&

- -

下面的代码是 && (逻辑与) 运算符的示例.

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

逻辑或(||

- -

下面的代码是 || (逻辑或) 运算符的示例。

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

逻辑非(!

- -

下面的代码是 ! (逻辑非) 运算符的示例.

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

双重非(!!)运算符

- -

可能使用双重非运算符的一个场景,是显式地将任意值强制转换为其对应的布尔值。这种转换是基于被转换值的 "truthyness" 和 "falsyness"的(参见 {{Glossary("truthy")}} 和 {{Glossary("falsy")}})。

- -

同样的转换可以通过 Boolean 函数完成。

- -
n1 = !!true                   // !!truthy 返回 true
-n2 = !!{}                     // !!truthy 返回 true: 任何 对象都是 truthy 的…
-n3 = !!(new Boolean(false))   // …甚至 .valueOf() 返回 false 的布尔值对象也是!
-n4 = !!false                  // !!falsy 返回 false
-n5 = !!""                     // !!falsy 返回 false
-n6 = !!Boolean(false)         // !!falsy 返回 false
-
- -

布尔值转换规则

- -

将 AND 转换为 OR

- -

以下涉及布尔运算的操作:

- -
bCondition1 && bCondition2
- -

总是等于:

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

将 OR 转换为 AND

- -

以下涉及布尔运算的操作:

- -
bCondition1 || bCondition2
- -

总是等于:

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

删除嵌套的小括号

- -

由于逻辑表达式是从左往右计算的,所以,通常可以按照下面的规则删除小括号。

- -

删除嵌套的 AND

- -

以下涉及布尔运算的操作:

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

总是等于:

- -
bCondition1 || bCondition2 && bCondition3
- -

删除嵌套的 OR

- -

以下涉及布尔运算的操作:

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

总是等于:

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

规范

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
规范状态备注
{{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/zh-cn/web/javascript/reference/operators/optional_chaining/index.html b/files/zh-cn/web/javascript/reference/operators/optional_chaining/index.html new file mode 100644 index 0000000000..da2f04c775 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/operators/optional_chaining/index.html @@ -0,0 +1,202 @@ +--- +title: 可选链操作符 +slug: Web/JavaScript/Reference/Operators/可选链 +tags: + - '?.' + - JavaScript + - Optional chaining (?.) + - Reference + - 参考 + - 可选链 + - 语言特性 + - 运算符 + - 链式调用 +translation_of: Web/JavaScript/Reference/Operators/Optional_chaining +--- +
{{JSSidebar("Operators")}}
+ +

可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish ) ({{JSxRef("null")}} 或者 {{JSxRef("undefined")}}) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined

+ +

当尝试访问可能不存在的对象属性时,可选链操作符将会使表达式更短、更简明。在探索一个对象的内容时,如果不能确定哪些属性必定存在,可选链操作符也是很有帮助的。

+ +
{{EmbedInteractiveExample("pages/js/expressions-optionalchainingoperator.html", "taller")}}
+ + + +

语法

+ +
obj?.prop
+obj?.[expr]
+arr?.[index]
+func?.(args)
+
+ +

描述

+ +

通过连接的对象的引用或函数可能是 undefinednull 时,可选链操作符提供了一种方法来简化被连接对象的值访问。

+ +

比如,思考一个存在嵌套结构的对象 obj。不使用可选链的话,查找一个深度嵌套的子属性时,需要验证之间的引用,例如:

+ +
let nestedProp = obj.first && obj.first.second;
+ +

为了避免报错,在访问obj.first.second之前,要保证 obj.first 的值既不是 null,也不是 undefined。如果只是直接访问 obj.first.second,而不对 obj.first 进行校验,则有可能抛出错误。

+ +

有了可选链操作符(?.),在访问 obj.first.second 之前,不再需要明确地校验 obj.first 的状态,再并用短路计算获取最终结果:

+ +
let nestedProp = obj.first?.second;
+ +

通过使用 ?. 操作符取代 . 操作符,JavaScript 会在尝试访问 obj.first.second 之前,先隐式地检查并确定 obj.first 既不是 null 也不是 undefined。如果obj.first null 或者 undefined,表达式将会短路计算直接返回 undefined

+ +

这等价于以下表达式,但实际上没有创建临时变量:

+ +
let temp = obj.first;
+let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);
+ +

可选链与函数调用

+ +

当尝试调用一个可能不存在的方法时也可以使用可选链。这将是很有帮助的,比如,当使用一个API的方法可能不可用时,要么因为实现的版本问题要么因为当前用户的设备不支持该功能。

+ +

函数调用时如果被调用的方法不存在,使用可选链可以使表达式自动返回undefined而不是抛出一个异常。

+ +
let result = someInterface.customMethod?.();
+ +
+

注意: 如果存在一个属性名且不是函数, 使用 ?. 仍然会产生一个 {{JSxRef("TypeError")}} 异常 (x.y is not a function).

+
+ +
+

注意: 如果 someInterface 自身是 null 或者 undefined ,异常 {{JSxRef("TypeError")}} 仍会被抛出 someInterface is null 如果你希望允许 someInterface 也为 null 或者 undefined ,那么你需要像这样写 someInterface?.customMethod?.()

+
+ +

处理可选的回调函数或者事件处理器

+ +

如果使用解构赋值来解构的一个对象的回调函数或 fetch 方法,你可能得到不能当做函数直接调用的不存在的值,除非你已经校验了他们的存在性。使用?.的你可以忽略这些额外的校验:

+ +
//  ES2019的写法
+function doSomething(onContent, onError) {
+  try {
+    // ... do something with the data
+  }
+  catch (err) {
+    if (onError) { // 校验onError是否真的存在
+      onError(err.message);
+    }
+  }
+}
+
+ +
// 使用可选链进行函数调用
+function doSomething(onContent, onError) {
+  try {
+   // ... do something with the data
+  }
+  catch (err) {
+    onError?.(err.message); // 如果onError是undefined也不会有异常
+  }
+}
+
+ +

可选链和表达式

+ +

当使用方括号与属性名的形式来访问属性时,你也可以使用可选链操作符:

+ +
let nestedProp = obj?.['prop' + 'Name'];
+ +

可选链不能用于赋值

+ +
let object = {};
+object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment
+ +

可选链访问数组元素

+ +
let arrayItem = arr?.[42];
+ +

例子

+ +

基本例子

+ +

如下的例子在一个不含 bar 成员的 Map 中查找 bar 成员的 name 属性,因此结果是 undefined

+ +
let myMap = new Map();
+myMap.set("foo", {name: "baz", desc: "inga"});
+
+let nameBar = myMap.get("bar")?.name;
+ +

短路计算

+ +

当在表达式中使用可选链时,如果左操作数是 nullundefined,表达式将不会被计算,例如:

+ +
let potentiallyNullObj = null;
+let x = 0;
+let prop = potentiallyNullObj?.[x++];
+
+console.log(x); // x 将不会被递增,依旧输出 0
+
+ +

连用可选链操作符

+ +

可以连续使用可选链读取多层嵌套结构:

+ +
let customer = {
+  name: "Carl",
+  details: {
+    age: 82,
+    location: "Paradise Falls" // details 的 address 属性未有定义
+  }
+};
+let customerCity = customer.details?.address?.city;
+
+// … 可选链也可以和函数调用一起使用
+let duration = vacations.trip?.getTime?.();
+
+ +

使用空值合并操作符

+ +

{{JSxRef("Operators/Nullish_Coalescing_Operator", "空值合并操作符")}}可以在使用可选链时设置一个默认值:

+ +
let customer = {
+  name: "Carl",
+  details: { age: 82 }
+};
+let customerCity = customer?.city ?? "暗之城";
+console.log(customerCity); // “暗之城”
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName('ESDraft', '#prod-OptionalExpression', 'optional expression')}}Stage 4
+ +

浏览器兼容性

+ +
+ + +

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

+ +

Implementation Progress

+ +

The following table provides a daily implementation status for this feature because this feature has not yet reached cross-browser stability. The data is generated by running the relevant feature tests in Test262, the standard test suite of JavaScript, in the nightly build, or the latest release of each browser's JavaScript engine.

+ +

{{EmbedTest262ReportResultsTable("optional-chaining")}}

+
+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/operators/pipeline_operator/index.html b/files/zh-cn/web/javascript/reference/operators/pipeline_operator/index.html new file mode 100644 index 0000000000..06ce40ad0b --- /dev/null +++ b/files/zh-cn/web/javascript/reference/operators/pipeline_operator/index.html @@ -0,0 +1,75 @@ +--- +title: 管道操作符 +slug: Web/JavaScript/Reference/Operators/管道操作符 +tags: + - Experimental + - JavaScript + - Operator + - 语法糖 + - 链式 + - 链式调用 +translation_of: Web/JavaScript/Reference/Operators/Pipeline_operator +--- +
{{jsSidebar("Operators")}} {{SeeCompatTable}}
+ +

试验性的管道操作符 |> (目前其标准化流程处于 stage 1 阶段)允许以一种易读的方式去对函数链式调用。本质上来说,管道操作符是单参数函数调用的语法糖,它允许你像这样执行一个调用:

+ +
let url = "%21" |> decodeURI;
+ +

使用传统语法写的话,等效的代码是这样的:

+ +
let url = decodeURI("%21");
+
+ +

语法

+ +
expression |> function
+ +

例子

+ +

函数链式调用

+ +

当链式调用多个函数时,使用管道操作符可以改善代码的可读性。

+ +
const double = (n) => n * 2;
+const increment = (n) => n + 1;
+
+// 没有用管道操作符
+double(increment(double(5))); // 22
+
+// 用上管道操作符之后
+5 |> double |> increment |> double; // 22
+
+ +

规范

+ + + + + + + + + + + + + + + + +
规范状态备注
Pipeline operator draftStage 1Not part of the ECMAScript specification yet.
+ +

浏览器兼容性Edit

+ +
+ + +

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

+
+ +

参见

+ + diff --git a/files/zh-cn/web/javascript/reference/operators/remainder/index.html b/files/zh-cn/web/javascript/reference/operators/remainder/index.html new file mode 100644 index 0000000000..276296ccd7 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/operators/remainder/index.html @@ -0,0 +1,81 @@ +--- +title: 取余 (%) +slug: Web/JavaScript/Reference/Operators/取余 +tags: + - JavaScript + - Language feature + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Remainder +--- +
{{jsSidebar("Operators")}}
+ +

当一个操作数除以第二个操作数时,取余运算符(%)返回剩余的余数。它与被除数的符号保持一致。

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

语法

+ +
Operator: var1 % var2
+
+ +

示例

+ +

被除数为正数

+ +
 12 % 5  //  2
+ 1 % -2 //  1
+ 1 % 2  //  1
+ 2 % 3  //  2
+5.5 % 2 // 1.5
+
+ +

被除数为负数

+ +
-12 % 5 // -2
+-1 % 2  // -1
+-4 % 2  // -0
+ +

被除数为NaN

+ +
NaN % 2 // NaN
+ +

规范

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-multiplicative-operators', 'Remainder operator')}}
+ +

浏览器兼容性

+ + + +

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

+ +

相关链接

+ + + + diff --git "a/files/zh-cn/web/javascript/reference/operators/\345\217\226\344\275\231/index.html" "b/files/zh-cn/web/javascript/reference/operators/\345\217\226\344\275\231/index.html" deleted file mode 100644 index 276296ccd7..0000000000 --- "a/files/zh-cn/web/javascript/reference/operators/\345\217\226\344\275\231/index.html" +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: 取余 (%) -slug: Web/JavaScript/Reference/Operators/取余 -tags: - - JavaScript - - Language feature - - Operator - - Reference -translation_of: Web/JavaScript/Reference/Operators/Remainder ---- -
{{jsSidebar("Operators")}}
- -

当一个操作数除以第二个操作数时,取余运算符(%)返回剩余的余数。它与被除数的符号保持一致。

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

语法

- -
Operator: var1 % var2
-
- -

示例

- -

被除数为正数

- -
 12 % 5  //  2
- 1 % -2 //  1
- 1 % 2  //  1
- 2 % 3  //  2
-5.5 % 2 // 1.5
-
- -

被除数为负数

- -
-12 % 5 // -2
--1 % 2  // -1
--4 % 2  // -0
- -

被除数为NaN

- -
NaN % 2 // NaN
- -

规范

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-multiplicative-operators', 'Remainder operator')}}
- -

浏览器兼容性

- - - -

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

- -

相关链接

- - - - diff --git "a/files/zh-cn/web/javascript/reference/operators/\345\217\257\351\200\211\351\223\276/index.html" "b/files/zh-cn/web/javascript/reference/operators/\345\217\257\351\200\211\351\223\276/index.html" deleted file mode 100644 index da2f04c775..0000000000 --- "a/files/zh-cn/web/javascript/reference/operators/\345\217\257\351\200\211\351\223\276/index.html" +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: 可选链操作符 -slug: Web/JavaScript/Reference/Operators/可选链 -tags: - - '?.' - - JavaScript - - Optional chaining (?.) - - Reference - - 参考 - - 可选链 - - 语言特性 - - 运算符 - - 链式调用 -translation_of: Web/JavaScript/Reference/Operators/Optional_chaining ---- -
{{JSSidebar("Operators")}}
- -

可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish ) ({{JSxRef("null")}} 或者 {{JSxRef("undefined")}}) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined

- -

当尝试访问可能不存在的对象属性时,可选链操作符将会使表达式更短、更简明。在探索一个对象的内容时,如果不能确定哪些属性必定存在,可选链操作符也是很有帮助的。

- -
{{EmbedInteractiveExample("pages/js/expressions-optionalchainingoperator.html", "taller")}}
- - - -

语法

- -
obj?.prop
-obj?.[expr]
-arr?.[index]
-func?.(args)
-
- -

描述

- -

通过连接的对象的引用或函数可能是 undefinednull 时,可选链操作符提供了一种方法来简化被连接对象的值访问。

- -

比如,思考一个存在嵌套结构的对象 obj。不使用可选链的话,查找一个深度嵌套的子属性时,需要验证之间的引用,例如:

- -
let nestedProp = obj.first && obj.first.second;
- -

为了避免报错,在访问obj.first.second之前,要保证 obj.first 的值既不是 null,也不是 undefined。如果只是直接访问 obj.first.second,而不对 obj.first 进行校验,则有可能抛出错误。

- -

有了可选链操作符(?.),在访问 obj.first.second 之前,不再需要明确地校验 obj.first 的状态,再并用短路计算获取最终结果:

- -
let nestedProp = obj.first?.second;
- -

通过使用 ?. 操作符取代 . 操作符,JavaScript 会在尝试访问 obj.first.second 之前,先隐式地检查并确定 obj.first 既不是 null 也不是 undefined。如果obj.first null 或者 undefined,表达式将会短路计算直接返回 undefined

- -

这等价于以下表达式,但实际上没有创建临时变量:

- -
let temp = obj.first;
-let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);
- -

可选链与函数调用

- -

当尝试调用一个可能不存在的方法时也可以使用可选链。这将是很有帮助的,比如,当使用一个API的方法可能不可用时,要么因为实现的版本问题要么因为当前用户的设备不支持该功能。

- -

函数调用时如果被调用的方法不存在,使用可选链可以使表达式自动返回undefined而不是抛出一个异常。

- -
let result = someInterface.customMethod?.();
- -
-

注意: 如果存在一个属性名且不是函数, 使用 ?. 仍然会产生一个 {{JSxRef("TypeError")}} 异常 (x.y is not a function).

-
- -
-

注意: 如果 someInterface 自身是 null 或者 undefined ,异常 {{JSxRef("TypeError")}} 仍会被抛出 someInterface is null 如果你希望允许 someInterface 也为 null 或者 undefined ,那么你需要像这样写 someInterface?.customMethod?.()

-
- -

处理可选的回调函数或者事件处理器

- -

如果使用解构赋值来解构的一个对象的回调函数或 fetch 方法,你可能得到不能当做函数直接调用的不存在的值,除非你已经校验了他们的存在性。使用?.的你可以忽略这些额外的校验:

- -
//  ES2019的写法
-function doSomething(onContent, onError) {
-  try {
-    // ... do something with the data
-  }
-  catch (err) {
-    if (onError) { // 校验onError是否真的存在
-      onError(err.message);
-    }
-  }
-}
-
- -
// 使用可选链进行函数调用
-function doSomething(onContent, onError) {
-  try {
-   // ... do something with the data
-  }
-  catch (err) {
-    onError?.(err.message); // 如果onError是undefined也不会有异常
-  }
-}
-
- -

可选链和表达式

- -

当使用方括号与属性名的形式来访问属性时,你也可以使用可选链操作符:

- -
let nestedProp = obj?.['prop' + 'Name'];
- -

可选链不能用于赋值

- -
let object = {};
-object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment
- -

可选链访问数组元素

- -
let arrayItem = arr?.[42];
- -

例子

- -

基本例子

- -

如下的例子在一个不含 bar 成员的 Map 中查找 bar 成员的 name 属性,因此结果是 undefined

- -
let myMap = new Map();
-myMap.set("foo", {name: "baz", desc: "inga"});
-
-let nameBar = myMap.get("bar")?.name;
- -

短路计算

- -

当在表达式中使用可选链时,如果左操作数是 nullundefined,表达式将不会被计算,例如:

- -
let potentiallyNullObj = null;
-let x = 0;
-let prop = potentiallyNullObj?.[x++];
-
-console.log(x); // x 将不会被递增,依旧输出 0
-
- -

连用可选链操作符

- -

可以连续使用可选链读取多层嵌套结构:

- -
let customer = {
-  name: "Carl",
-  details: {
-    age: 82,
-    location: "Paradise Falls" // details 的 address 属性未有定义
-  }
-};
-let customerCity = customer.details?.address?.city;
-
-// … 可选链也可以和函数调用一起使用
-let duration = vacations.trip?.getTime?.();
-
- -

使用空值合并操作符

- -

{{JSxRef("Operators/Nullish_Coalescing_Operator", "空值合并操作符")}}可以在使用可选链时设置一个默认值:

- -
let customer = {
-  name: "Carl",
-  details: { age: 82 }
-};
-let customerCity = customer?.city ?? "暗之城";
-console.log(customerCity); // “暗之城”
- -

规范

- - - - - - - - - - - - - - - - -
规范状态备注
{{SpecName('ESDraft', '#prod-OptionalExpression', 'optional expression')}}Stage 4
- -

浏览器兼容性

- -
- - -

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

- -

Implementation Progress

- -

The following table provides a daily implementation status for this feature because this feature has not yet reached cross-browser stability. The data is generated by running the relevant feature tests in Test262, the standard test suite of JavaScript, in the nightly build, or the latest release of each browser's JavaScript engine.

- -

{{EmbedTest262ReportResultsTable("optional-chaining")}}

-
- -

参见

- - diff --git "a/files/zh-cn/web/javascript/reference/operators/\346\214\211\344\275\215\344\270\216/index.html" "b/files/zh-cn/web/javascript/reference/operators/\346\214\211\344\275\215\344\270\216/index.html" deleted file mode 100644 index 20eece2691..0000000000 --- "a/files/zh-cn/web/javascript/reference/operators/\346\214\211\344\275\215\344\270\216/index.html" +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: 按位与 (&) -slug: Web/JavaScript/Reference/Operators/按位与 -translation_of: Web/JavaScript/Reference/Operators/Bitwise_AND ---- -
{{jsSidebar("Operators")}}
- -

按位与运算符 (&) 在每个位上返回 1 ,这两个操作数对应的位都是 1.

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

语法

- -
a & b
-
- -

描述

- -

操作数被转换为32位整数,并由一系列位(0和1)表示。 超过32位的数字将丢弃其最高有效位。 例如,以下大于32位的整数将被转换为32位整数:

- -
Before: 11100110111110100000000000000110000000000001
-After:              10100000000000000110000000000001
- -

第一个操作数中的每个位都与第二个操作数中的相应位配对:第一位到第一位,第二位到第二位,依此类推。

- -

将运算符应用于每对位,然后按位构造结果。

- -

与运算的真值表:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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)
-
- -

将任何数字x0进行按位与运算将得出0

- -

示例

- -

使用按位与

- -
// 5: 00000000000000000000000000000101
-// 2: 00000000000000000000000000000010
-5 & 2; // 0
- -

规范说明

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#prod-BitwiseANDExpression', 'Bitwise AND expression')}}
- -

浏览器兼容性

- - - -

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

- -

参阅

- - diff --git "a/files/zh-cn/web/javascript/reference/operators/\347\233\270\345\212\240/index.html" "b/files/zh-cn/web/javascript/reference/operators/\347\233\270\345\212\240/index.html" deleted file mode 100644 index 6da432b4e6..0000000000 --- "a/files/zh-cn/web/javascript/reference/operators/\347\233\270\345\212\240/index.html" +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: 相加运算符 (+) -slug: Web/JavaScript/Reference/Operators/相加 -translation_of: Web/JavaScript/Reference/Operators/Addition ---- -
{{jsSidebar("相加运算符")}}
- -

相加运算符 (+) 用于对两个操作数进行相加运算,如果操作数为字符串则该运算符将两个操作数连接成一个字符串。

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

语法

- -
表达式: x + y
-
- -

示例

- -

数字的相加运算

- -
// Number + Number -> addition
-1 + 2 // 3
-
-// Boolean + Number -> addition
-true + 1 // 2
-
-// Boolean + Boolean -> addition
-false + false // 0
-
- -

字符串相加运算

- -
// String + String -> concatenation
-'foo' + 'bar' // "foobar"
-
-// Number + String -> concatenation
-5 + 'foo' // "5foo"
-
-// String + Boolean -> concatenation
-'foo' + false // "foofalse"
- -

注: '+'两侧只要有一侧是字符串,另一侧的数字则会自动转换成字符串,因为其中存在隐式转换

- -

规范

- - - - - - - - - - -
规范
{{SpecName('ESDraft', '#sec-addition-operator-plus', 'Addition operator')}}
- -

浏览器兼容性

- - - -

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

- -

参考

- - diff --git "a/files/zh-cn/web/javascript/reference/operators/\347\233\270\347\255\211/index.html" "b/files/zh-cn/web/javascript/reference/operators/\347\233\270\347\255\211/index.html" deleted file mode 100644 index e100ec1d2d..0000000000 --- "a/files/zh-cn/web/javascript/reference/operators/\347\233\270\347\255\211/index.html" +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: 相等(==) -slug: Web/JavaScript/Reference/Operators/相等 -tags: - - JavaScript - - Reference -translation_of: Web/JavaScript/Reference/Operators/Equality ---- -
{{jsSidebar("Operators")}}
- -

等于运算符(==)检查其两个操作数是否相等,并返回Boolean结果。与严格相等运算符(===)不同,它会尝试强制类型转换并且比较不同类型的操作数。

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

语法

- -
x == y
-
- -

描述

- -

相等运算符(==!=)使用抽象相等比较算法比较两个操作数。可以大致概括如下:

- - - -

此运算符与严格等于===)运算符之间最显着的区别在于,严格等于运算符不尝试类型转换。相反,严格相等运算符始终将不同类型的操作数视为不同。

- -

例子

- -

没有类型转换的比较

- -
1 == 1;              // true
-"hello" == "hello";  // true
- -

与类型转换比较

- -
"1" ==  1;            // true
-1 == "1";             // true
-0 == false;           // true
-0 == null;            // false
-0 == undefined;       // false
-null == undefined;    // true
-
-const number1 = new Number(3);
-const number2 = new Number(3);
-number1 == 3;         // true
-number1 == number2;   // false
- -

对象比较

- -
const object1 = {"key": "value"}
-const object2 = {"key": "value"};
-
-object1 == object2 // false
-object2 == object2 // true
- -

比较字符串和String对象

- -

请注意,使用构造的字符串new String()是对象。如果将其中之一与字符串文字进行比较,则该String对象将被转换为字符串文字并对其内容进行比较。但是,如果两个操作数都是String对象,则将它们作为对象进行比较,并且必须引用相同的对象才能进行比较:

- -
const string1 = "hello";
-const string2 = String("hello");
-const string3 = new String("hello");
-const string4 = new String("hello");
-
-console.log(string1 == string2); // true
-console.log(string1 == string3); // true
-console.log(string2 == string3); // true
-console.log(string3 == string4); // false
-console.log(string4 == string4); // true
- -

比较日期和字符串

- -
const d = new Date('December 17, 1995 03:24:00');
-const s = d.toString(); // for example: "Sun Dec 17 1995 03:24:00 GMT-0800 (Pacific Standard Time)"
-console.log(d == s);    //true
- -

技术指标

- - - - - - - - - - - - -
规范
{{SpecName('ESDraft', '#sec-equality-operators', 'Equality operators')}}
- -

浏览器兼容性

- -

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

- -

参见

- - diff --git "a/files/zh-cn/web/javascript/reference/operators/\347\256\241\351\201\223\346\223\215\344\275\234\347\254\246/index.html" "b/files/zh-cn/web/javascript/reference/operators/\347\256\241\351\201\223\346\223\215\344\275\234\347\254\246/index.html" deleted file mode 100644 index 06ce40ad0b..0000000000 --- "a/files/zh-cn/web/javascript/reference/operators/\347\256\241\351\201\223\346\223\215\344\275\234\347\254\246/index.html" +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: 管道操作符 -slug: Web/JavaScript/Reference/Operators/管道操作符 -tags: - - Experimental - - JavaScript - - Operator - - 语法糖 - - 链式 - - 链式调用 -translation_of: Web/JavaScript/Reference/Operators/Pipeline_operator ---- -
{{jsSidebar("Operators")}} {{SeeCompatTable}}
- -

试验性的管道操作符 |> (目前其标准化流程处于 stage 1 阶段)允许以一种易读的方式去对函数链式调用。本质上来说,管道操作符是单参数函数调用的语法糖,它允许你像这样执行一个调用:

- -
let url = "%21" |> decodeURI;
- -

使用传统语法写的话,等效的代码是这样的:

- -
let url = decodeURI("%21");
-
- -

语法

- -
expression |> function
- -

例子

- -

函数链式调用

- -

当链式调用多个函数时,使用管道操作符可以改善代码的可读性。

- -
const double = (n) => n * 2;
-const increment = (n) => n + 1;
-
-// 没有用管道操作符
-double(increment(double(5))); // 22
-
-// 用上管道操作符之后
-5 |> double |> increment |> double; // 22
-
- -

规范

- - - - - - - - - - - - - - - - -
规范状态备注
Pipeline operator draftStage 1Not part of the ECMAScript specification yet.
- -

浏览器兼容性Edit

- -
- - -

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

-
- -

参见

- - diff --git "a/files/zh-cn/web/javascript/reference/operators/\350\207\252\345\207\217/index.html" "b/files/zh-cn/web/javascript/reference/operators/\350\207\252\345\207\217/index.html" deleted file mode 100644 index f405740df3..0000000000 --- "a/files/zh-cn/web/javascript/reference/operators/\350\207\252\345\207\217/index.html" +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: 自减 (--) -slug: Web/JavaScript/Reference/Operators/自减 -tags: - - JavaScript - - 自减 - - 语法特性 - - 运算符 -translation_of: Web/JavaScript/Reference/Operators/Decrement ---- -
{{jsSidebar("Operators")}}
- -

 自减运算符(--) 将它的操作数减一,然后返回操作数.

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


- 语法

- -
操作符: x-- or --x
-
- -

语法细节

- -

如果使用后缀式,即将操作符放在操作数的后面 (如,x--),运算会减一,然后返回减一之前的值。

- -

如果使用前缀式,即将操作符放在操作数的前面 (如,--x),运算会减一,然后返回减一之后的值。

- -

示例

- -

后缀式

- -
let x = 3;
-y = x--;
-
-// y = 3
-// x = 2
-
- -

前缀式

- -
let a = 2;
-b = --a;
-
-// a = 1
-// b = 1
-
- -

规范

- - - - - - - - - - -
规范
{{SpecName('ESDraft', '#sec-postfix-decrement-operator', '自减运算符')}}
- -


- 浏览器兼容性

- - - -

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

- -

相关链接

- - diff --git "a/files/zh-cn/web/javascript/reference/operators/\351\200\273\350\276\221\345\222\214/index.html" "b/files/zh-cn/web/javascript/reference/operators/\351\200\273\350\276\221\345\222\214/index.html" deleted file mode 100644 index de38317f42..0000000000 --- "a/files/zh-cn/web/javascript/reference/operators/\351\200\273\350\276\221\345\222\214/index.html" +++ /dev/null @@ -1,137 +0,0 @@ ---- -title: 逻辑与(&&) -slug: Web/JavaScript/Reference/Operators/逻辑和 -translation_of: Web/JavaScript/Reference/Operators/Logical_AND ---- -
{{jsSidebar("Operators")}}
- -

The logical AND (&&) operator (logical conjunction) for a set of operands is true if and only if all of its operands are true. It is typically used with {{jsxref("Boolean")}} (logical) values. When it is, it returns a Boolean value. However, the && operator actually returns the value of one of the specified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value.

- -
{{EmbedInteractiveExample("pages/js/expressions-logical-and.html", "shorter")}}
- - - -

Syntax

- -
expr1 && expr2
-
- -

Description

- -

If expr1 can be converted to true, returns expr2; else, returns expr1.

- -

If a value can be converted to true, the value is so-called {{Glossary("truthy")}}. If a value can be converted to false, the value is so-called {{Glossary("falsy")}}.

- -

Examples of expressions that can be converted to false are:

- - - -

Even though the && operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the {{jsxref("Global_Objects/Boolean/Boolean", "Boolean")}} constructor.

- -

Short-circuit evaluation

- -

The logical AND expression is evaluated left to right, it is tested for possible "short-circuit" evaluation using the following rule:

- -

(some falsy expression) && expr is short-circuit evaluated to the falsy expression;

- -

Short circuit means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). This happens because the value of the operator is already determined after the evaluation of the first operand. See example:

- -
function A(){ console.log('called A'); return false; }
-function B(){ console.log('called B'); return true; }
-
-console.log( A() && B() );
-// logs "called A" due to the function call,
-// then logs false (which is the resulting value of the operator)
-
- -

Operator precedence

- -

The following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence).

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

Examples

- -

Using AND

- -

The following code shows examples of the && (logical AND) operator.

- -
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
- -

Conversion rules for booleans

- -

Converting AND to OR

- -

The following operation involving booleans:

- -
bCondition1 && bCondition2
- -

is always equal to:

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

Converting OR to AND

- -

The following operation involving booleans:

- -
bCondition1 || bCondition2
- -

is always equal to:

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

Removing nested parentheses

- -

As logical expressions are evaluated left to right, it is always possible to remove parentheses from a complex expression following some rules.

- -

The following composite operation involving booleans:

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

is always equal to:

- -
bCondition1 || bCondition2 && bCondition3
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#prod-LogicalANDExpression', 'Logical AND expression')}}
- -

Browser compatibility

- - - -

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

- -

See also

- - diff --git a/files/zh-cn/web/javascript/reference/reserved_words/index.html b/files/zh-cn/web/javascript/reference/reserved_words/index.html deleted file mode 100644 index 0d52110bfa..0000000000 --- a/files/zh-cn/web/javascript/reference/reserved_words/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Reserved Words -slug: Web/JavaScript/Reference/Reserved_words -translation_of: Web/JavaScript/Reference/Lexical_grammar#Keywords -translation_of_original: Web/JavaScript/Reference/Reserved_Words ---- -

 

- -

以下这些是ECMAScript规范已经规定的关键字,不能用作变量、函数名、过程、和对象名:

- - - -

以下是ECMAScript规定的保留字:

- - - -

请注意,虽然ECMA-262还没有正式规定,但是在Mozilla中const,export和import已经被作为保留字对待。

- -
cn:Core JavaScript 1.5 Reference:Reserved Words - -

 

-
- -

{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/Reserved_Words" } ) }}

diff --git a/files/zh-cn/web/javascript/reference/statements/default/index.html b/files/zh-cn/web/javascript/reference/statements/default/index.html deleted file mode 100644 index 12e076166c..0000000000 --- a/files/zh-cn/web/javascript/reference/statements/default/index.html +++ /dev/null @@ -1,120 +0,0 @@ ---- -title: default -slug: Web/JavaScript/Reference/Statements/default -tags: - - JavaScript - - Keyword -translation_of: Web/JavaScript/Reference/Statements/switch -translation_of_original: Web/JavaScript/Reference/Statements/default ---- -
{{jsSidebar("Statements")}}
- -
- -

default 关键字可以在 JavaScript 的两种情况下使用:在 {{jsxref("Statements/switch", "switch")}} ,或 {{jsxref("Statements/export", "export")}} 中。

- -

语法

- -

在{{jsxref("Statements/switch", "switch")}} 语句中使用:

- -
switch (expression) {
-  case value1:
-    //当表达式的值和value1匹配执行这里的语句
-    [break;]
-  default:
-    //当表达式的值没有匹配,执行这里的语句
-    [break;]
-}
- -

在{{jsxref("Statements/export", "export")}} 中使用:

- -
export default nameN 
- -

描述

- -

更多细节,参见

- - - -

示例

- -

switch语句中使用default

- -

在以下示例中,如果expr为“Oranges”或“Apples”,程序将匹配“Oranges”或“Apples”的值并执行相应的声明。在任何其它情况下,default关键字将执行关联的语句。

- -
switch (expr) {
-  case "Oranges":
-    console.log("Oranges are $0.59 a pound.");
-    break;
-  case "Apples":
-    console.log("Apples are $0.32 a pound.");
-    break;
-  default:
-    console.log("Sorry, we are out of " + expr + ".");
-}
- -

export语句中使用default

- -

如果要导出单个值或需要模块的回调值,则可以使用默认导出: 

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

然后,在另一个脚本中,默认导出将直接被导入:

- -
// module "my-module.js"
-import myFunction from 'my-module';
-console.log(myFunction(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")}}

- -

See also

- - diff --git a/files/zh-cn/web/javascript/reference/template_literals/index.html b/files/zh-cn/web/javascript/reference/template_literals/index.html new file mode 100644 index 0000000000..aec3adfb5b --- /dev/null +++ b/files/zh-cn/web/javascript/reference/template_literals/index.html @@ -0,0 +1,261 @@ +--- +title: 模板字符串 +slug: Web/JavaScript/Reference/template_strings +tags: + - ECMAScript6 + - JavaScript + - Template string + - 模板字符串 +translation_of: Web/JavaScript/Reference/Template_literals +--- +
{{JsSidebar("More")}} 
+ +

模板字面量 是允许嵌入表达式的字符串字面量。你可以使用多行字符串和字符串插值功能。它们在ES2015规范的先前版本中被称为“模板字符串”。

+ +

语法

+ +
`string text`
+
+`string text line 1
+ string text line 2`
+
+`string text ${expression} string text`
+
+tag `string text ${expression} string text`
+
+ +

描述

+ +

模板字符串使用反引号 (` `) 来代替普通字符串中的用双引号和单引号。模板字符串可以包含特定语法(${expression})的占位符。占位符中的表达式和周围的文本会一起传递给一个默认函数,该函数负责将所有的部分连接起来,如果一个模板字符串由表达式开头,则该字符串被称为带标签的模板字符串,该表达式通常是一个函数,它会在模板字符串处理后被调用,在输出最终结果前,你都可以通过该函数来对模板字符串进行操作处理。在模版字符串内使用反引号(`)时,需要在它前面加转义符(\)。

+ +
`\`` === "`" // --> true
+ +

多行字符串

+ +

在新行中插入的任何字符都是模板字符串中的一部分,使用普通字符串,你可以通过以下的方式获得多行字符串:

+ +
console.log('string text line 1\n' +
+'string text line 2');
+// "string text line 1
+// string text line 2"
+ +

要获得同样效果的多行字符串,只需使用如下代码:

+ +
console.log(`string text line 1
+string text line 2`);
+// "string text line 1
+// string text line 2"
+ +

插入表达式

+ +

在普通字符串中嵌入表达式,必须使用如下语法:

+ +

 

+ +
var a = 5;
+var b = 10;
+console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
+// "Fifteen is 15 and
+// not 20."
+ +

 

+ +

现在通过模板字符串,我们可以使用一种更优雅的方式来表示:

+ +

 

+ +
var a = 5;
+var b = 10;
+console.log(`Fifteen is ${a + b} and
+not ${2 * a + b}.`);
+// "Fifteen is 15 and
+// not 20."
+ +

 

+ +

嵌套模板

+ +

在某些时候,嵌套模板是具有可配置字符串的最简单也是更可读的方法。 在模板中,只需在模板内的占位符 ${ } 内使用它们,就可以轻松地使用内部反引号。 例如,如果条件 a 是真的,那么返回这个模板化的文字。

+ +

ES5:

+ +
var classes = 'header'
+classes += (isLargeScreen() ?
+   '' : item.isCollapsed ?
+     ' icon-expander' : ' icon-collapser');
+ +

在ES2015中使用模板文字而没有嵌套:

+ +
const classes = `header ${ isLargeScreen() ? '' :
+    (item.isCollapsed ? 'icon-expander' : 'icon-collapser') }`;
+
+ +

 

+ +

在ES2015的嵌套模板字面量中:

+ +

 

+ +
const classes = `header ${ isLargeScreen() ? '' :
+ `icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`;
+ +

 

+ +

 

+ +

带标签的模板字符串

+ +

更高级的形式的模板字符串是带标签的模板字符串。标签使您可以用函数解析模板字符串。标签函数的第一个参数包含一个字符串值的数组。其余的参数与表达式相关。最后,你的函数可以返回处理好的的字符串(或者它可以返回完全不同的东西 , 如下个例子所述)。用于该标签的函数的名称可以被命名为任何名字。

+ +
var person = 'Mike';
+var age = 28;
+
+function myTag(strings, personExp, ageExp) {
+
+  var str0 = strings[0]; // "that "
+  var str1 = strings[1]; // " is a "
+
+  // There is technically a string after
+  // the final expression (in our example),
+  // but it is empty (""), so disregard.
+  // var str2 = strings[2];
+
+  var ageStr;
+  if (ageExp > 99){
+    ageStr = 'centenarian';
+  } else {
+    ageStr = 'youngster';
+  }
+
+  return str0 + personExp + str1 + ageStr;
+
+}
+
+var output = myTag`that ${ person } is a ${ age }`;
+
+console.log(output);
+// that Mike is a youngster
+ +

正如下面例子所展示的,标签函数并不一定需要返回一个字符串。

+ +
function template(strings, ...keys) {
+  return (function(...values) {
+    var dict = values[values.length - 1] || {};
+    var result = [strings[0]];
+    keys.forEach(function(key, i) {
+      var value = Number.isInteger(key) ? values[key] : dict[key];
+      result.push(value, strings[i + 1]);
+    });
+    return result.join('');
+  });
+}
+
+var t1Closure = template`${0}${1}${0}!`;
+t1Closure('Y', 'A');  // "YAY!"
+var t2Closure = template`${0} ${'foo'}!`;
+t2Closure('Hello', {foo: 'World'});  // "Hello World!"
+ +

原始字符串

+ +

在标签函数的第一个参数中,存在一个特殊的属性raw ,我们可以通过它来访问模板字符串的原始字符串,而不经过特殊字符的替换。

+ +
function tag(strings) {
+  console.log(strings.raw[0]);
+}
+
+tag`string text line 1 \n string text line 2`;
+// logs "string text line 1 \n string text line 2" ,
+// including the two characters '\' and 'n'
+ +

另外,使用{{jsxref("String.raw()")}} 方法创建原始字符串和使用默认模板函数和字符串连接创建是一样的。

+ +
var str = String.raw`Hi\n${2+3}!`;
+// "Hi\n5!"
+
+str.length;
+// 6
+
+str.split('').join(',');
+// "H,i,\,n,5,!"
+
+ +

带标签的模版字面量及转义序列

+ +

自ES2016起,带标签的模版字面量遵守以下转义序列的规则:

+ + + +

这表示类似下面这种带标签的模版是有问题的,因为对于每一个ECMAScript语法,解析器都会去查找有效的转义序列,但是只能得到这是一个形式错误的语法:

+ +
latex`\unicode`
+// 在较老的ECMAScript版本中报错(ES2016及更早)
+// SyntaxError: malformed Unicode character escape sequence
+
+ +

ES2018关于非法转义序列的修订

+ +

带标签的模版字符串应该允许嵌套支持常见转义序列的语言(例如DSLsLaTeX)。ECMAScript提议模版字面量修订(第4阶段,将要集成到ECMAScript 2018标准) 移除对ECMAScript在带标签的模版字符串中转义序列的语法限制。

+ +

不过,非法转义序列在"cooked"当中仍然会体现出来。它们将以 {{jsxref("undefined")}} 元素的形式存在于"cooked"之中:

+ +
function latex(str) {
+ return { "cooked": str[0], "raw": str.raw[0] }
+}
+
+latex`\unicode`
+
+// { cooked: undefined, raw: "\\unicode" }
+ +

值得注意的是,这一转义序列限制只对带标签的模板字面量移除,而不包括不带标签的模板字面量:

+ +
let bad = `bad escape sequence: \unicode`;
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-template-literals', 'Template Literals')}}{{Spec2('ES2015')}}Initial definition. Defined in several section of the specification: Template Literals, Tagged Templates
{{SpecName('ESDraft', '#sec-template-literals', 'Template Literals')}}{{Spec2('ESDraft')}}Defined in several section of the specification: Template Literals, Tagged Templates
Template Literal RevisionStage 4 draftDrops escape sequence restriction from tagged templates
+ +

浏览器兼容

+ +
+ + +

{{Compat("javascript.grammar.template_literals")}}

+
+ +

相关链接

+ + diff --git a/files/zh-cn/web/javascript/reference/template_strings/index.html b/files/zh-cn/web/javascript/reference/template_strings/index.html deleted file mode 100644 index aec3adfb5b..0000000000 --- a/files/zh-cn/web/javascript/reference/template_strings/index.html +++ /dev/null @@ -1,261 +0,0 @@ ---- -title: 模板字符串 -slug: Web/JavaScript/Reference/template_strings -tags: - - ECMAScript6 - - JavaScript - - Template string - - 模板字符串 -translation_of: Web/JavaScript/Reference/Template_literals ---- -
{{JsSidebar("More")}} 
- -

模板字面量 是允许嵌入表达式的字符串字面量。你可以使用多行字符串和字符串插值功能。它们在ES2015规范的先前版本中被称为“模板字符串”。

- -

语法

- -
`string text`
-
-`string text line 1
- string text line 2`
-
-`string text ${expression} string text`
-
-tag `string text ${expression} string text`
-
- -

描述

- -

模板字符串使用反引号 (` `) 来代替普通字符串中的用双引号和单引号。模板字符串可以包含特定语法(${expression})的占位符。占位符中的表达式和周围的文本会一起传递给一个默认函数,该函数负责将所有的部分连接起来,如果一个模板字符串由表达式开头,则该字符串被称为带标签的模板字符串,该表达式通常是一个函数,它会在模板字符串处理后被调用,在输出最终结果前,你都可以通过该函数来对模板字符串进行操作处理。在模版字符串内使用反引号(`)时,需要在它前面加转义符(\)。

- -
`\`` === "`" // --> true
- -

多行字符串

- -

在新行中插入的任何字符都是模板字符串中的一部分,使用普通字符串,你可以通过以下的方式获得多行字符串:

- -
console.log('string text line 1\n' +
-'string text line 2');
-// "string text line 1
-// string text line 2"
- -

要获得同样效果的多行字符串,只需使用如下代码:

- -
console.log(`string text line 1
-string text line 2`);
-// "string text line 1
-// string text line 2"
- -

插入表达式

- -

在普通字符串中嵌入表达式,必须使用如下语法:

- -

 

- -
var a = 5;
-var b = 10;
-console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
-// "Fifteen is 15 and
-// not 20."
- -

 

- -

现在通过模板字符串,我们可以使用一种更优雅的方式来表示:

- -

 

- -
var a = 5;
-var b = 10;
-console.log(`Fifteen is ${a + b} and
-not ${2 * a + b}.`);
-// "Fifteen is 15 and
-// not 20."
- -

 

- -

嵌套模板

- -

在某些时候,嵌套模板是具有可配置字符串的最简单也是更可读的方法。 在模板中,只需在模板内的占位符 ${ } 内使用它们,就可以轻松地使用内部反引号。 例如,如果条件 a 是真的,那么返回这个模板化的文字。

- -

ES5:

- -
var classes = 'header'
-classes += (isLargeScreen() ?
-   '' : item.isCollapsed ?
-     ' icon-expander' : ' icon-collapser');
- -

在ES2015中使用模板文字而没有嵌套:

- -
const classes = `header ${ isLargeScreen() ? '' :
-    (item.isCollapsed ? 'icon-expander' : 'icon-collapser') }`;
-
- -

 

- -

在ES2015的嵌套模板字面量中:

- -

 

- -
const classes = `header ${ isLargeScreen() ? '' :
- `icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`;
- -

 

- -

 

- -

带标签的模板字符串

- -

更高级的形式的模板字符串是带标签的模板字符串。标签使您可以用函数解析模板字符串。标签函数的第一个参数包含一个字符串值的数组。其余的参数与表达式相关。最后,你的函数可以返回处理好的的字符串(或者它可以返回完全不同的东西 , 如下个例子所述)。用于该标签的函数的名称可以被命名为任何名字。

- -
var person = 'Mike';
-var age = 28;
-
-function myTag(strings, personExp, ageExp) {
-
-  var str0 = strings[0]; // "that "
-  var str1 = strings[1]; // " is a "
-
-  // There is technically a string after
-  // the final expression (in our example),
-  // but it is empty (""), so disregard.
-  // var str2 = strings[2];
-
-  var ageStr;
-  if (ageExp > 99){
-    ageStr = 'centenarian';
-  } else {
-    ageStr = 'youngster';
-  }
-
-  return str0 + personExp + str1 + ageStr;
-
-}
-
-var output = myTag`that ${ person } is a ${ age }`;
-
-console.log(output);
-// that Mike is a youngster
- -

正如下面例子所展示的,标签函数并不一定需要返回一个字符串。

- -
function template(strings, ...keys) {
-  return (function(...values) {
-    var dict = values[values.length - 1] || {};
-    var result = [strings[0]];
-    keys.forEach(function(key, i) {
-      var value = Number.isInteger(key) ? values[key] : dict[key];
-      result.push(value, strings[i + 1]);
-    });
-    return result.join('');
-  });
-}
-
-var t1Closure = template`${0}${1}${0}!`;
-t1Closure('Y', 'A');  // "YAY!"
-var t2Closure = template`${0} ${'foo'}!`;
-t2Closure('Hello', {foo: 'World'});  // "Hello World!"
- -

原始字符串

- -

在标签函数的第一个参数中,存在一个特殊的属性raw ,我们可以通过它来访问模板字符串的原始字符串,而不经过特殊字符的替换。

- -
function tag(strings) {
-  console.log(strings.raw[0]);
-}
-
-tag`string text line 1 \n string text line 2`;
-// logs "string text line 1 \n string text line 2" ,
-// including the two characters '\' and 'n'
- -

另外,使用{{jsxref("String.raw()")}} 方法创建原始字符串和使用默认模板函数和字符串连接创建是一样的。

- -
var str = String.raw`Hi\n${2+3}!`;
-// "Hi\n5!"
-
-str.length;
-// 6
-
-str.split('').join(',');
-// "H,i,\,n,5,!"
-
- -

带标签的模版字面量及转义序列

- -

自ES2016起,带标签的模版字面量遵守以下转义序列的规则:

- - - -

这表示类似下面这种带标签的模版是有问题的,因为对于每一个ECMAScript语法,解析器都会去查找有效的转义序列,但是只能得到这是一个形式错误的语法:

- -
latex`\unicode`
-// 在较老的ECMAScript版本中报错(ES2016及更早)
-// SyntaxError: malformed Unicode character escape sequence
-
- -

ES2018关于非法转义序列的修订

- -

带标签的模版字符串应该允许嵌套支持常见转义序列的语言(例如DSLsLaTeX)。ECMAScript提议模版字面量修订(第4阶段,将要集成到ECMAScript 2018标准) 移除对ECMAScript在带标签的模版字符串中转义序列的语法限制。

- -

不过,非法转义序列在"cooked"当中仍然会体现出来。它们将以 {{jsxref("undefined")}} 元素的形式存在于"cooked"之中:

- -
function latex(str) {
- return { "cooked": str[0], "raw": str.raw[0] }
-}
-
-latex`\unicode`
-
-// { cooked: undefined, raw: "\\unicode" }
- -

值得注意的是,这一转义序列限制只对带标签的模板字面量移除,而不包括不带标签的模板字面量:

- -
let bad = `bad escape sequence: \unicode`;
- -

规范

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-template-literals', 'Template Literals')}}{{Spec2('ES2015')}}Initial definition. Defined in several section of the specification: Template Literals, Tagged Templates
{{SpecName('ESDraft', '#sec-template-literals', 'Template Literals')}}{{Spec2('ESDraft')}}Defined in several section of the specification: Template Literals, Tagged Templates
Template Literal RevisionStage 4 draftDrops escape sequence restriction from tagged templates
- -

浏览器兼容

- -
- - -

{{Compat("javascript.grammar.template_literals")}}

-
- -

相关链接

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