Reflect objects in JavaScript (ES6 new features) _javascript tips

Source: Internet
Author: User
Tags extend object object wrapper

Reflect Introduction:

Reflect this object has not yet been implemented in my node (v4.4.3), Babel (6.7.7) is not implemented, the new version of Chrome is supported, and FF has supported proxy and reflect earlier, To have node support reflect can install harmony-reflect;

Reflect is not a constructor, it is called directly through Reflect.method (), reflect some methods are similar to the proxy, and most of the native object of the reflect method has been implemented again.

What to use reflect

Here are a few reasons why to use reflect, translation address: reflect, probably translated again:

1: More useful return value: reflect some methods are the same as the object method in ES5, such as: Reflect.getownpropertydescriptor and Reflect.defineproperty, however, Object.defineproperty (obj, name, desc) execution succeeds in returning obj, and other causes of the error, Reflect.defineproperty only returns false or true to indicate whether the object's properties are set, and the following code can be refactored:

try {
object.defineproperty (obj, name, desc);
Property defined successfully
} catch (e) {
//possible failure (and might accidentally catch the wrong excepti ON)
}

The weight constitutes this:

if (Reflect.defineproperty (obj, name, desc)) {
//Success
} else {
//Failure
}

The rest of the methods, such as Relect.set, Reflect.deleteproperty, Reflect.preventextensions, reflect.setprototypeof, can be reconstructed;

2: function operation, if you want to determine that an obj has defined or inherited attribute name, in the ES5 this judgment: name in obj;

or delete a property: Delete Obj[name], although these are very useful, very short, very clear, but to use the time to be encapsulated into a class;

With reflect, it encapsulates you, Reflect.has (obj, name), Reflect.deleteproperty (obj, name);

3: More reliable function execution way: In Es, to execute a function f, and give it a set of parameters args, but also to bind this word, to write:

F.apply (obj, args)

But F's apply may be redefined as a user's own apply, so it is more plausible to write:

Function.prototype.apply.call (f, obj, args)

The above code is too long and difficult to understand, with the reflect, we can be shorter and more concise and clear:

Reflect.apply (f, obj, args)

4: Constructor of variable Parameter form: Imagine, you want to instantiate a constructor with an indeterminate length parameter, and in ES5 we can use the extension notation to write:

var obj = new F (... args)

In ES5, however, the extension is not supported Ah, so we can only use f.apply, or F.call way to pass different parameters, but F is a constructor, this is a pit dad, but with reflect,

We can write this in ES5:

var obj = reflect.construct (F, args)

5: Control accessor or reader of this: in ES5, you want to read an element's properties or set properties like this:

var name = ...//Get property name as a string
obj[name]//Generic Property lookup

The Updatereflect.get and Reflect.set methods allow us to do the same thing, and he adds an additional parameter to the reciver that allows us to set the object's setter and getter's up and down this:

var name = ...//Get property name as a string
reflect.get (obj, name, wrapper)//If obj[name] are an accessor, it get s run with ' this = = Wrapper '
reflect.set (obj, name, value, wrapper) accessor does not want to use its own method, but wants to redirect this to wrapper:
var obj = {
set foo (value) {return This.bar ();},
bar:function () {
alert (1);
}
};
var wrapper = {
bar:function () {
Console.log ("wrapper");
}
Reflect.set (obj, "foo", "value", wrapper);

6: Avoid direct access to __proto__:

ES5 provides object.getprototypeof (obj) to access the object's prototypes, ES6 offers also provides

Reflect.getprototypeof (obj) and reflect.setprototypeof (obj, Newproto), which is the new way to access and set the object's prototype:

The use of reflect.apply

Reflect.apply is actually ES5 in the Function.prototype.apply () double, the implementation of reflect.apply requires three parameters

The first parameter is: The function to be executed;

The second parameter is: the context in which the function needs to be executed.

The third parameter is: an array or pseudo array, which is used as an argument to execute the function;

<script> let fn = function () {this.attr = [0,1,2,3];};
Let obj = {}; 
Reflect.apply (FN, obj, []) console.log (obj); </script> reflect.apply Demo: <script> reflect.apply (Math.floor, Undefined, [1.75]);
Output: 1; Reflect.apply (String.fromCharCode, Undefined, [104, 101, 108, 108, 111]); Output: "Hello" reflect.apply (RegExp.prototype.exec,/ab/, ["confabulation"]). Index; Output: 4 reflect.apply ("" "CharAt," ponies ", [3]);
Output: "I" </script>reflect can be used in conjunction with proxy: {var Fn = function () {};
Fn.prototype.run = function () {Console.log ("runs Out"); var proxyfn = new Proxy (Fn, {construct (target, arugments) {Console.log ("Proxy constructor"); var obj = new Target (... ar
ugments);
The use method of reflect.apply;
Reflect.apply (Target.prototype.run, obj, arugments);
return obj;
}
}); New Proxyfn (); Will first output: "Proxy constructor"; and then output: the use of runs Out}reflect.construct (): Reflect.construct is actually an instantiated constructor, implemented in the form of a reference, and executed in a different way, The effect is the same, the first parameter of construct is a constructor, the second parameter consists of an array of parameters or a pseudo array, the basic method is: var Fn = FuNction (arg) {This.args = [arg]}; Console.log (New Fn (1), reflect.construct (fn,[1));
Output is the same as var d = reflect.construct (Date, [1776, 6, 4]); D instanceof Date; True D.getfullyear ();
1776//So reflect.consturct and new constructs so reflect.consturct and new constructors are the same, at least so far. We can give reflect.construct a third argument, the third parameter is a superclass, and the new element inherits the superclass; <script> function Someconstructor () {} var result = reflect.
Construct (Array, [], someconstructor); Reflect.getprototypeof (result); Someconstructor.prototype Array.isarray (Result);
True//or var Fn = function () {this.attr = [1];};
var person = function () {};
Person.prototype.run = function () {};
Console.log (Reflect.construct (Fn, [], person)); </script> so we can use this to implement a special array that inherits arrays, but also has its own method; var Fn = function () {array.apply (this, arguments); this.shot = () =& Gt
{Console.log ("Heheda");};
};
The use of var arr = reflect.construct (Fn, []) Reflect.defineproperty;
Reflect.defineproperty returns a Boolean value that adds a property and property value to an object by directly assigning it to an entire object, and if the addition fails, the error is thrown; var obj = {}; obj.x = 10;
Console.log (obj.x)/output: 10; add value using Reflect.defineproperty; <script> var obj = {}; if (Reflect.defineproperty (obj, "x", {value:7})) {Console.log ("added Success");}
else{Console.log ("Add failed"); </script> If we execute preventextensions, we can define the new attribute by object.defindproperty the error, but there is no error through Reflect.defineproperty.
Returns a value of false: var obj = {};
Object.preventextensions (obj);
Object.defineproperty (obj, "x", {value:101, Writable:false, Enumerable:false, configurable:false});/directly wrong; Console.log (Reflect.defineproperty (obj, "x", {value:101}))//Return FALSE: Returns the value of the setting, regardless of whether the value is assigned correctly, by way of a direct assignment.
Unless we manually confirm that the object's property value is set successfully; <script> var obj = {};
Object.preventextensions (obj); Console.log (OBJ.AA = 1);
Output: 1; Console.log (OBJ.AA)/output: undefined </script>reflect.deleteproperty use: Reflect.deleteproperty and Reflect.defineproperty Use the same method, Reflect.deleteproperty and delete obj.xx the same operation, The difference is to use different forms: one is an operator, the other is a function call; Reflect.deleteproperty (Object.freeze ({foo:1}), "foo"); False Delete Object.freeze({foo:1}). foo;
Output: The False;reflect.get () method has two necessary parameters for using this method: The first is obj target object, the second is the property name object, the third is optional, and is the context of the reader (this);
var obj = {};
Obj.foo = 1; Console.log (Obj.foo);
Output: 1; Console.log (obj, "foo")//output: 1; If Reflect.get has a third parameter, the third argument is the context of the reader: var reflect = require ('
Harmony-reflect ');
var obj = {"Foo": 1, get Bar () {return this.foo;}};
var foo = {};
Foo.foo = "Heheda";
Console.log (Reflect.get (obj, "bar", Foo));
Use of the Reflect.getownpropertydescritptor () method: Get the attribute description by Reflect.getownpropertydescritptor:
Reflect.getownpropertydescriptor ({x: "Hello"}, "X");
You can also get: Object.getownpropertydescriptor ({x: "1"}, "X"); The difference between the two is that one will wrap the object, one will not: Reflect.getownpropertydescriptor ("Hello", 0); Throws an exception Object.getownpropertydescriptor ("Hello", 0);
Output: {value: "H", Writable:false, Enumerable:true, configurable:false}reflect.getprototypeof () method use: Reflect.getprototypeof and object.getprototypeof are the same, they are all returning an object's prototype reflect.getprototypeof ({}); Output: Object.prototype reflect.getprototypeof (Object.proToType); Output: null reflect.getprototypeof (Object.create (null));
Output: Nullreflect.has using Reflect.has This method is a bit like an operator: in, for example: xx in obj; <script> Reflect.has ({x:0}, "X")//output: true; Reflect.has ({y:0}, "Y")/output: true; var obj = {x:0}; Console.log ("x" in obj);  var proxy = new Proxy (obj, {has:function (target, args) {Console.log ("Execute has method"); return Reflect.has (target,... args); }); Console.log ("x" in proxy); Output: true; Console.log (Reflect.has (Proxy, "X"))/output: true; </script> This demo's obj is equivalent to a method, no use for him,
Just took advantage of his has method: obj = new Proxy ({}, {has (T, K) {return K.startswith ("door");}}); Reflect.has (obj, "doorbell"); True Reflect.has (obj, "dormitory");
False reflect.isextensible () use//Now this element can be extended; var empty = {}; Reflect.isextensible (empty);
= = = TRUE//using the Preventextensions method so that the object cannot extend the new attribute; reflect.preventextensions (empty); Reflect.isextensible (empty);
= = = False//This object cannot extend new attributes, writable properties can still be changed var sealed = Object.seal ({}); Reflect.isextensible (sealed); = = = FalsE//This object is completely frozen var frozen = Object.freeze ({}); Reflect.isextensible (frozen); = = = The difference between falsereflect.isextensible and object.isextensible is that if the argument is wrong, one throws the wrong and the other only returns TRUE or False:Reflect.isExtensible (1)
;
Misplaced: 1 is isn't an object object.isextensible (1); returns false;
The use of Reflect.ownkeys () method: Reflect.ownkeys, object can not Ownkeys method, reflect.ownkeysz his role is to return the object of the keys; Console.log (Reflect.ownkeys ({"A": 0, "B": 1, "C": 2, "D": 3})); Output: ["A", "B", "C", "D"] Console.log (Reflect.ownkeys ([]));
["Length"] var sym = symbol.for ("Comet");
var sym2 = symbol.for ("meteor");
var obj = {[Sym]: 0, "str": 0, "773": 0, "0": 0, [sym2]: 0, "-1": 0, "8": 0, "second str": 0}; Reflect.ownkeys (obj); Output:/["0", "8", "773", "str", "1", "second str", symbol (comet), symbol (meteor)]reflect.ownkeys sort is based on: first display number, number by size
, then the string is sorted according to the order of insertion, and finally the symbol type key is sorted according to the insertion order;
This is sorted because, when you assign a property to an object, the collation of the key of the object is the first number, the string, and the symbol type data, and the Reflect.preventextensions () method: Object also has Preventextensions method, and Reflect.preventextensions () has a little difference, if REFLEct.preventextensions arguments are not objects that can be thrown incorrectly; var empty = {}; Reflect.isextensible (empty);
= = = TRUE//The object after preventextensions can be modified; reflect.preventextensions (empty); Reflect.isextensible (empty);
= = = False Reflect.preventextensions (1);
Typeerror:1 is isn't an object object.preventextensions (1);
Will not be thrown wrong, will return: 1reflect.set () Reflect.set method and get is the same; var obj = {}; Reflect.set (obj, "prop", "value"); Output: True Console.log (Obj.prop);
Output: "value" var arr = ["Duck", "duck", "duck"]; Reflect.set (arr, 2, "Goose"); True Console.log (arr[2]); "Goose" Reflect.set (arr, "Length", 1); True Console.log (arr);//["Duck"];
Reflect.set (obj) is equivalent to Reflect.set (obj, undefined, undefined);
var obj = {}; Reflect.set (obj);
Output: TRUE//above code is equivalent to Reflect.set (obj, undefined, undefined);
Reflect.getownpropertydescriptor (obj, "undefined");
{value:undefined, writable:true, Enumerable:true, Configurable:true}reflect.set can also have a fourth parameter, which will act as this for the stter; var obj = {value:10, set key (value) {Console.log ("setTer ");
This.value = value;
The Get key () {return this.value;}};
Reflect.set (obj, "key", "Heheda", obj); Console.log (obj);
The reflect.setprototypeof () reflect.setprototypeof () method is almost the same as object.setprototypeof, which sets the object to a prototype, which is to change the __proto__ property of the object ...; Reflect.setprototypeof ({}, Object.prototype);
The output true//Is NULL for the object array [[Prototype]]. Reflect.setprototypeof ({}, NULL); True//The obj.__proto__ at this time is undefine//After the object is frozen reset [[prototype]] Reflect.setprototypeof (Object.freeze ({}), NULL);
False//returns FALSE if the prototype chain is circular dependent.
var target = {};
var proto = Object.create (target); Reflect.setprototypeof (target, Proto); False

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.