From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../global_objects/reflect/apply/index.html | 143 ++++++++++++++++++ .../global_objects/reflect/construct/index.html | 151 +++++++++++++++++++ .../reflect/defineproperty/index.html | 97 ++++++++++++ .../reference/global_objects/reflect/index.html | 166 +++++++++++++++++++++ .../global_objects/reflect/set/index.html | 146 ++++++++++++++++++ 5 files changed, 703 insertions(+) create mode 100644 files/pt-br/web/javascript/reference/global_objects/reflect/apply/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/reflect/construct/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/reflect/defineproperty/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/reflect/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/reflect/set/index.html (limited to 'files/pt-br/web/javascript/reference/global_objects/reflect') diff --git a/files/pt-br/web/javascript/reference/global_objects/reflect/apply/index.html b/files/pt-br/web/javascript/reference/global_objects/reflect/apply/index.html new file mode 100644 index 0000000000..08621fe798 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/reflect/apply/index.html @@ -0,0 +1,143 @@ +--- +title: Reflect.apply() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/apply +tags: + - ECMAScript6 + - JavaScript + - Reflect + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/apply +--- +
{{JSRef}}
+ +

O método estático Reflect.apply() chama uma função alvo com os argumentos especificados.

+ +

Sintaxe

+ +
Reflect.apply(target, thisArgument, argumentsList)
+
+ +

Parâmetros

+ +
+
target
+
Função que será chamada.
+
thisArgument
+
O valor de "this" que será usado pela function do target.
+
argumentsList
+
Um objeto do tipo array que especifica os argumentos com que o target deve ser chamado.
+
+ +

Valor de retorno

+ +

O resultado da função alvo chamada com o this  e argumentos especificados.

+ +

Exceções

+ +

Um {{jsxref("TypeError")}}, se a função especificada no target não for invocável.

+ +

Descrição

+ +

No ES5, tipicamente é usado o método {{jsxref("Function.prototype.apply()")}} para chamar uma função com o valor de this e argumentos fornecidos como um array (ou um array-like object).

+ +
Function.prototype.apply.call(Math.floor, undefined, [1.75]);
+ +

Com o Reflect.apply isso se torna menos verboso e mais fácil de entender.

+ +

Exemplos

+ +

Usando Reflect.apply()

+ +
Reflect.apply(Math.floor, undefined, [1.75]);
+// 1;
+
+Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]);
+// "hello"
+
+Reflect.apply(RegExp.prototype.exec, /ab/, ["confabulation"]).index;
+// 4
+
+Reflect.apply("".charAt, "ponies", [3]);
+// "i"
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES6', '#sec-reflect.apply', 'Reflect.apply')}}{{Spec2('ES6')}}Definição inicial.
{{SpecName('ESDraft', '#sec-reflect.apply', 'Reflect.apply')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support49{{CompatGeckoDesktop(42)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(42)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/reflect/construct/index.html b/files/pt-br/web/javascript/reference/global_objects/reflect/construct/index.html new file mode 100644 index 0000000000..dece94c79a --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/reflect/construct/index.html @@ -0,0 +1,151 @@ +--- +title: Reflect.construct() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/construct +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/construct +--- +
{{JSRef}}
+ +

The static Reflect.construct() method acts like the new operator, but as a function. It is equivalent to calling new target(...args). It gives also the added option to specify a different prototype.

+ +
{{EmbedInteractiveExample("pages/js/reflect-construct.html")}}
+ + + +

Sintaxe

+ +
Reflect.construct(target, argumentsList[, newTarget])
+
+ +

Parametros

+ +
+
target
+
A função alvo à ser chamada.
+
argumentsList
+
Um objeto tipo array que especifica com quais argumentos target deveria ser chamada.
+
newTarget {{optional_inline}}
+
O construtor de quem o protótipo deveria ser usado. Veja também o new.target operador. Se newTarget não estiver presente, será target.
+
+ +

Return value

+ +

A new instance of target (or newTarget, if present), initialized by target as a constructor with the given arguments.

+ +

Exceptions

+ +

A {{jsxref("TypeError")}}, if target or newTarget are not constructors.

+ +

Description

+ +

Reflect.construct allows you to invoke a constructor with a variable number of arguments (which would also be possible by using the spread operator combined with the new operator).

+ +
var obj = new Foo(...args);
+var obj = Reflect.construct(Foo, args);
+
+ +

 

+ +

Reflect.construct() vs Object.create()

+ +

Prior to the introduction of Reflect, objects could be constructed using an arbitrary combination of constructor and prototype by using Object.create().

+ +
function OneClass() {
+    this.name = 'one';
+}
+
+function OtherClass() {
+    this.name = 'other';
+}
+
+// Calling this:
+var obj1 = Reflect.construct(OneClass, args, OtherClass);
+
+// ...has the same result as this:
+var obj2 = Object.create(OtherClass.prototype);
+OneClass.apply(obj2, args);
+
+console.log(obj1.name); // 'one'
+console.log(obj2.name); // 'one'
+
+console.log(obj1 instanceof OneClass); // false
+console.log(obj2 instanceof OneClass); // false
+
+console.log(obj1 instanceof OtherClass); // true
+console.log(obj2 instanceof OtherClass); // true
+
+ +

However, while the end result is the same, there is one important difference in the process. When using Object.create() and Function.prototype.apply(), the new.target operator will point to undefined within the function used as the constructor, since the new keyword is not being used to create the object.

+ +

When invoking Reflect.construct(), on the other hand, the new.target operator will point to the newTarget parameter if supplied, or target if not.

+ +
function OneClass() {
+    console.log('OneClass');
+    console.log(new.target);
+}
+function OtherClass() {
+    console.log('OtherClass');
+    console.log(new.target);
+}
+
+var obj1 = Reflect.construct(OneClass, args);
+// Output:
+//     OneClass
+//     function OneClass { ... }
+
+var obj2 = Reflect.construct(OneClass, args, OtherClass);
+// Output:
+//     OneClass
+//     function OtherClass { ... }
+
+var obj3 = Object.create(OtherClass.prototype);
+OneClass.apply(obj3, args);
+// Output:
+//     OneClass
+//     undefined
+ +

 

+ +

Examples

+ +

Using Reflect.construct()

+ +
var d = Reflect.construct(Date, [1776, 6, 4]);
+d instanceof Date; // true
+d.getFullYear(); // 1776
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-reflect.construct', 'Reflect.construct')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-reflect.construct', 'Reflect.construct')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Reflect.construct")}}

+ +

See also

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/reflect/defineproperty/index.html b/files/pt-br/web/javascript/reference/global_objects/reflect/defineproperty/index.html new file mode 100644 index 0000000000..c4b56f02ca --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/reflect/defineproperty/index.html @@ -0,0 +1,97 @@ +--- +title: Reflect.defineProperty() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/defineProperty +tags: + - ECMAScript 2015 + - JavaScript + - Referencia + - Reflect + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/defineProperty +--- +
{{JSRef}}
+ +

O método estático Reflect.defineProperty() é como o {{jsxref("Object.defineProperty()")}}, mas retorna um {{jsxref("Boolean")}}.

+ +
{{EmbedInteractiveExample("pages/js/reflect-defineproperty.html")}}
+ + + +

Sintaxe

+ +
Reflect.defineProperty(target, propertyKey, attributes)
+
+ +

Parâmetros

+ +
+
target
+
O objeto de destino onde será definida a propriedade.
+
propertyKey
+
O nome da propriedade a ser definida ou modificada.
+
attributes
+
Os atributos para a propriedade que está sendo definida ou modificada.
+
+ +

Valor de retorno

+ +

Um {{jsxref("Boolean")}} indicando se a propriedade foi ou não definida com êxito.

+ +

Erros

+ +

Um {{jsxref("TypeError")}}, se target não for um {{jsxref("Object")}}.

+ +

Descrição

+ +

O método Reflect.defineProperty permite a adição precisa ou a modificação de uma propriedade em um objeto. Para mais detalhes veja o {{jsxref("Object.defineProperty")}}, que é semelhante.

+ +
+

Uma diferença fundamental: Object.defineProperty retorna o objeto ou lança um {{jsxref ("TypeError")}} se a propriedade não tiver sido definida com êxito. Reflect.defineProperty, no entanto, simplesmente retorna um {{jsxref ("Boolean")}} indicando se a propriedade foi ou não definida com êxito.

+
+ +

Exemplos

+ +

Usando Reflect.defineProperty()

+ +
let obj = {}
+Reflect.defineProperty(obj, 'x', {value: 7})  // true
+obj.x                                         // 7
+
+ +

Verificando se a definição da propriedade foi bem-sucedida

+ +

Com o {{jsxref ("Object.defineProperty")}}, que retorna um objeto se for bem-sucedido ou lança um {{jsxref ("TypeError")}}, você usaria um bloco try...catch para detectar qualquer erro que ocorreu ao definir uma propriedade.

+ +

Como Reflect.defineProperty retorna um status de sucesso booleano, você pode usar apenas um bloco if...else aqui:

+ +
if (Reflect.defineProperty(target, property, attributes)) {
+  // success
+} else {
+  // failure
+}
+ +

Especificações

+ + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-reflect.defineproperty', 'Reflect.defineProperty')}}
+ +

Compatibilidade do navegador

+ + + +

{{Compat("javascript.builtins.Reflect.defineProperty")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/reflect/index.html b/files/pt-br/web/javascript/reference/global_objects/reflect/index.html new file mode 100644 index 0000000000..e001709367 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/reflect/index.html @@ -0,0 +1,166 @@ +--- +title: Reflect +slug: Web/JavaScript/Reference/Global_Objects/Reflect +tags: + - ECMAScript6 + - JavaScript + - NeedsTranslation + - Overview + - Reflect + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect +--- +
{{JSRef}}
+ +

Reflect é um objeto nativo que provê métodos para operações JavaScript interceptáveis. Os métodos são os mesmos que o dos manipuladores de Proxy. Reflect não é um objeto de função, então não é construtível.

+ +

Descrição

+ +

Ao contrário da maioria dos objetos globais, Reflect não é um construtor. Você não pode usá-lo com o operador new ou invocar o objeto Reflect como uma função. Todas as propriedades e métodos do Reflect são estáticos (igual o objeto {{jsxref("Math")}}).

+ +

O objeto Reflect provê as seguintes funções estáticas as quais tem os mesmos nomes usados pelos métodos manipuladores de Proxy.

+ +

Alguns deste métodos são também os mesmos correspondentes aos métodos em {{jsxref("Object")}}, embora eles tenham diferenças sutis entre eles.

+ +

Métodos

+ +
+
{{jsxref("Reflect.apply()", "Reflect.apply(targetthisArgumentargumentsList)")}}
+
Chama uma função de destino com os argumentos, conforme especificado pelo parâmetro argumentsList. Veja também {{jsxref("Function.prototype.apply()")}}.
+
{{jsxref("Reflect.construct()", "Reflect.construct(targetargumentsList[, newTarget])")}}
+
 O operador new como uma função. Equivalente a chamada new target(...args). Também possui a opção de especificar um prototype diferente
+
{{jsxref("Reflect.defineProperty()", "Reflect.defineProperty(targetpropertyKeyattributes)")}}
+
Similar ao {{jsxref("Object.defineProperty()")}}. Retorna um {{jsxref("Boolean")}} com o valor true se a propriedade foi definida com sucesso.
+
{{jsxref("Reflect.deleteProperty()", "Reflect.deleteProperty(targetpropertyKey)")}}
+
O operador delete como uma função. Equivalente a chamada delete target[name].
+
{{jsxref("Reflect.get()")}}, "Reflect.get(targetpropertyKey[, receiver])"}}
+
Uma função que retorna o valor da propriedade. Funciona como obter uma propriedade de um objeto (target[propertyKey]) como uma função.
+
{{jsxref("Reflect.getOwnPropertyDescriptor()", "Reflect.getOwnPropertyDescriptor(targetpropertyKey)")}}
+
Similar ao {{jsxref("Object.getOwnPropertyDescriptor()")}}. Retorna um descritor de propriedade da propriedade dada se existir no objeto, {{jsxref ("undefined")}} caso contrário.
+
{{jsxref("Reflect.getPrototypeOf()", "Reflect.getPrototypeOf(target)")}}
+
Igual ao {{jsxref("Object.getPrototypeOf()")}}.
+
{{jsxref("Reflect.has()", "Reflect.has(target, propertyKey)")}}
+
O operador in como função. Retorna um {{jsxref("Boolean")}} indicando se existe uma propriedade própria ou herdada.
+
{{jsxref("Reflect.isExtensible()", "Reflect.isExtensible(target)")}}
+
Igual ao {{jsxref("Object.isExtensible()")}}. Returna um {{jsxref("Boolean")}} com o valor true se o destino (parâmetro target) for extensível.
+
{{jsxref("Reflect.ownKeys()", "Reflect.ownKeys(target)")}}
+
Retorna uma matriz das chaves de propriedade do próprio objeto de destino (não herdadas).
+
{{jsxref("Reflect.preventExtensions()", "Reflect.preventExtensions(target)")}}
+
Similar ao {{jsxref("Object.preventExtensions()")}}. Retorna um {{jsxref("Boolean")}} com o valor true se a atualização foi bem sucedida.
+
{{jsxref("Reflect.set()", "Reflect.set(targetpropertyKeyvalue[, receiver])")}}
+
Uma função que atribui valores a propriedades. Retorna um {{jsxref ("Boolean")}} com o valor true se a atualização foi bem sucedida.
+
{{jsxref("Reflect.setPrototypeOf()", "Reflect.setPrototypeOf(targetprototype)")}}
+
Uma função que define o protótipo de um objeto. Retorna um {{jsxref ("Boolean")}} com o valor true se a atualização foi bem sucedida.
+
+

Exemplos

+ +

Verificando se um objeto contém determinadas propriedades

+ +
const duck = {
+  name: 'Maurice',
+  color: 'white',
+  greeting: function() {
+    console.log(`Quaaaack! My name is ${this.name}`);
+  }
+}
+
+Reflect.has(duck, 'color');
+// true
+Reflect.has(duck, 'haircut');
+// false
+ +

Retornando as próprias chaves do objeto

+ +
Reflect.ownKeys(duck);
+// [ "name", "color", "greeting" ]
+ +

Adicionando uma nova propriedade ao objeto

+ +
Reflect.set(duck, 'eyes', 'black');
+// returns "true" if successful
+// "duck" now contains the property "eyes: 'black'"
+
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentário
{{SpecName('ES6', '#sec-reflect-object', 'Reflect')}}{{Spec2('ES6')}}Definição Inicial
{{SpecName('ESDraft', '#sec-reflect-object', 'Reflect')}}{{Spec2('ESDraft')}}Reflect.enumerate foi removido.
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("42")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(49.0)}}{{CompatChrome(49.0)}}{{CompatGeckoMobile("42")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/reflect/set/index.html b/files/pt-br/web/javascript/reference/global_objects/reflect/set/index.html new file mode 100644 index 0000000000..45022b89d1 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/reflect/set/index.html @@ -0,0 +1,146 @@ +--- +title: Reflect.set() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/set +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/set +--- +
{{JSRef}}
+ +

O método estático Reflect.set() define uma propriedade em um objeto.

+ +

Sintaxe

+ +
Reflect.set(alvo, propriedade, valor[, receptor])
+
+ +

Parâmetros

+ +
+
alvo
+
O objeto alvo onde a propriedade será definida.
+
propriedade
+
O nome da propriedade a ser definida.
+
valor
+
o valor a ser definido para a propriedade.
+
receptor
+
+

O valor do this fornecido para a chamada do alvo se um setter é encontrado.

+
+
+ +

Retorno

+ +

Um {{jsxref("Boolean")}} indicando se a definicão da propriedade ocorreu com sucesso ou não.

+ +

Exceções

+ +

Um {{jsxref("TypeError")}}, se o alvo não for um {{jsxref("Object")}}.

+ +

Descrição

+ +

O método Reflect.set permite que você defina uma propriedade em um objeto. Ele define a propriedade e is like the property accessor syntax as a function.

+ +

Examplos

+ +

Usando Reflect.set()

+ +
// Object
+var obj = {};
+Reflect.set(obj, "prop", "value"); // true
+obj.prop; // "value"
+
+// Array
+var arr = ["duck", "duck", "duck"];
+Reflect.set(arr, 2, "goose"); // true
+arr[2]; // "goose"
+
+// É possível truncar o array
+Reflect.set(arr, "length", 1); // true
+arr; // ["duck"];
+
+// Com apenas um argumento, propertKey e valor são undefined
+var obj = {};
+Reflect.set(obj); // true
+Reflect.getOwnPropertyDescriptor(obj, "undefined");
+// { value: undefined, writable: true, enumerable: true, configurable: true }
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-reflect.set', 'Reflect.set')}}{{Spec2('ES6')}}Definição inicial.
{{SpecName('ESDraft', '#sec-reflect.set', 'Reflect.set')}}{{Spec2('ESDraft')}} 
+ +

Compatilibidade com navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support49{{CompatGeckoDesktop(42)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(42)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja também

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