Reflect Introduction:
The Reflect object has not been implemented in my node (v4.4.3), and babel (6.7.7) is not implemented. The new version of chrome is supported. ff has supported Proxy and Reflect for a long time. If you want node to support Reflect, you can install harmony-reflect;
Reflect is not a constructor. When you want to use it, it is called directly through (). Some methods of Reflect are similar to Proxy, and most Reflect methods native Objects have been re-implemented.
What to use Reflect
Here are a few reasons why Reflect is used. Translation address: Reflect, roughly translated:
1: More useful return value: Reflect has some methods like the Object method in ES5, such as: and, but, (obj, name, desc) will return obj if executed successfully, and other errors will only return false or true to indicate whether the object's properties have been set. The following code can be refactored:
try { (obj, name, desc); // property defined successfully } catch (e) { // possible failure (and might accidentally catch the wrong exception) }
Reconstructed like this:
if ((obj, name, desc)) { // success } else { // failure }
The other methods, such as , , , can be refactored;
2: Function operation. If you want to determine that an obj has a defined or inherits the attribute name, you can judge it in ES5 like this: name in obj;
Or delete an attribute: delete obj[name]. Although these are very useful, very short and clear, they must also be encapsulated into a class when they are to be used;
With Reflect, it helps you encapsulate, (obj, name), (obj, name);
3: More reliable functional execution method: In ES, if you want to execute a function f and pass a set of parameters args to it, and bind this, you need to write this:
(obj, args)
However, the f application may be redefined as the user's own application, so it is more reliable to write this way:
(f, obj, args)
The above code is too long and difficult to understand. With Reflect, we can be shorter and more concise and clearer:
(f, obj, args)
4: Constructors in variadic parameter form: Imagine that you want to instantiate a constructor through parameters of uncertain length. In ES5, we can use extension symbols, which can be written like this:
var obj = new F(...args)
However, in ES5, extension characters are not supported, so we can only use or pass different parameters. Unfortunately, F is a constructor, which is a scam, but with Reflect,
We can write this in ES5:
var obj = (F, args)
5: This controls the accessor or reader: In ES5, if you want to read the attributes of an element or set the attributes, you must do this:
var name = ... // get property name as a string obj[name] // generic property lookup obj[name] = value // generic property
And the method allows us to do the same thing, and it adds an extra parameter to the recciver, which allows us to set the object's setter and getter up and down this:
var name = ... // get property name as a string (obj, name, wrapper) // if obj[name] is an accessor, it gets run with `this === wrapper` (obj, name, value, wrapper)Don't want to use your own method in the accessor,Instead, want to redirectthisarrivewrapper: var obj = { set foo(value) { return (); }, bar: function() { alert(1); } }; var wrapper = { bar : function() { ("wrapper"); } } (obj, "foo", "value", wrapper);
6: Avoid direct access to __proto__:
ES5 provides (obj), to access the prototype of the object, and ES6 provides also provides
(obj) and (obj, newProto), this is a new way to access and set the prototype of an object:
Use
In fact, it is the () substitute in ES5. Three parameters are required to execute it.
The first parameter is: the function to be executed;
The second parameter is: The context this that needs to be executed;
The third parameter is: is an array or pseudo-array, which will be used as a parameter to execute the function;
<script> let fn = function() { = [0,1,2,3]; }; let obj = {}; (fn, obj, []) (obj); </script> ofDEMO: <script> (, undefined, [1.75]); // Output: 1;(, undefined, [104, 101, 108, 108, 111]); // Output: "hello"(, /ab/, ["confabulation"]).index; //Output: 4("".charAt, "ponies", [3]); // Output: "i"</script>ReflectCan be withProxyJoint use: { var Fn = function(){ }; = function() { ( "runs out" ); }; var ProxyFn = new Proxy(Fn, { construct (target ,arugments) { ("proxy constructor"); var obj = new target(...arugments); How to use //;(, obj, arugments); return obj; } }); new ProxyFn (); //The output will be: "proxy constructor" first; then output: runs out}()of使用: In fact, it is instantiated constructor,通过传参形式of实现, 执行of方式不同, The effect is actually the same, constructof第一个参数为构造函数, 第二个参数由参数组成of数组或者伪数组, 基本of使用method为: var Fn = function(arg) { = [arg] }; ( new Fn(1), (Fn,[1]) ); // The output is the samevar d = (Date, [1776, 6, 4]); d instanceof Date; // true (); // 1776 //So it is the same as new constructor, at least so far...We can pass the third parameter , The third parameter is a superclass, The new element will inherit this super class; <script> function someConstructor() {} var result = (Array, [], someConstructor); (result); // (result); // true //or var Fn = function() { = [1]; }; var Person = function() { }; = function() { }; ( (Fn, [], Person) ); </script> 所以我们可以用这个实现一个特殊ofof数组, Inheriting arrays, 但是There are also自己ofmethod; var Fn = function() { (this, arguments); = ()=> { ("heheda"); }; }; var arr = (Fn, [])of使用; 返回of是一个布尔值, 通过直接赋值of方式把属性and属性值添加给对象返回of是一整个对象, If the addition fails, it will throw an error; var obj = {}; = 10; () //Output: 10; Add value in the way you use;<script> var obj = {}; if( (obj, "x", {value : 7 }) ) { ("added success"); }else{ ("Add failed"); }; </script>If we executepreventExtensions, An error was reported by defining a new attribute, But there is no error, Returned onefalseof值: var obj = {}; (obj); (obj, "x" , { value: 101, writable: false, enumerable: false, configurable: false });// Throw it wrongly;( (obj, "x", {value:101}) ) //Return false: If the value is assigned directly, the set value will be returned regardless of whether the value is assigned correctly, unless we manually confirm whether the property value of the object is set successfully;<script> var obj = {}; (obj); ( = 1 ); //Output: 1;() //Output: undefined;</script>of使用: andof使用method差不多, and delete of操作结果是一样, The difference is that the usage form is different:One is the operator,One is a function call; (({foo: 1}), "foo"); // false delete ({foo: 1}).foo; //Output: false; use of () method这个methodof有两个必须of参数: The first one isobjTarget object, The second one is the attribute name object, 第三个是可选of,是作为读取器of上下文(this); var obj = {}; = 1; ( ); //Output: 1;( (obj, "foo") ) //Output: 1; If there is a third parameter, the third parameter will be used as the context of the reader:var Reflect = require('harmony-reflect'); var obj = { "foo" : 1, get bar() { return ; } }; var foo = {}; = "heheda"; ((obj, "bar", foo)); ()methodof使用: Get attribute description: ({x: "hello"}, "x"); //You can also get it like this:({x:"1"},"x"); //The difference between these two is that one can wrap the object, and the other cannot:("hello",0); //throw an exception("hello",0); //Output: {value: "h", writable: false, enumerable: true, configurable: false}() method usage:and是一样of, 他们都是返回一个对象of原型 ({}); // Output:(); // Output: null((null)); // Output: UseThis method is a bit like an operator:in , For example: xx in obj; <script> ({x:0}, "x") //Output: true;({y:0}, "y") //Output: true; var obj = {x:0}; ( "x" in obj); var proxy = new Proxy(obj, { has : function(target, args) { ("Execute has method"); return (target,...args); } }); ( "x" in proxy); //Output: true; ((proxy, "x")) //Output: true; </script>The obj of this demo is equivalent to becoming a method, it is useless, it just uses its has method:obj = new Proxy({}, { has(t, k) { return ("door"); } }); (obj, "doorbell"); // true (obj, "dormitory"); // false ()of使用 // Now this element can be expanded;var empty = {}; (empty); // === true // Use preventExtensions method to prevent this object from extending new properties;(empty); (empty); // === false // This object cannot expand new attributes, writable attributes can still be changedvar sealed = ({}); (sealed); // === false // This object is completely frozenvar frozen = ({}); (frozen); // === The difference is that if the parameter is incorrect, one will throw the wrong one, and the other will just return true or false:(1); // The wrong throw: 1 is not an object(1); // Return false;() method usage:, ObjectBut noownKeysmethod, 他of作用是返回对象ofkeys; (({"a":0,"b":1,"c":2,"d":3})); //Output: ["a", "b", "c", "d"](([])); // ["length"] var sym = ("comet"); var sym2 = ("meteor"); var obj = {[sym]: 0, "str": 0, "773": 0, "0": 0, [sym2]: 0, "-1": 0, "8": 0, "second str": 0}; (obj); //Output: / [ "0", "8", "773", "str", "-1", "second str", Symbol(comet), Symbol(meteor) ] is sorted by: first display the numbers, the numbers are sorted by size, then the strings are sorted by the order of insertion, and finally the key of the symbol type is also sorted by the order of insertion;The sorting appears because,When you assign a value to an object property, 对象ofkeyof排序规则就是先数字, In string, Finallysymbol类型of数据; ()of使用method: ObjectThere are alsopreventExtensionsmethod, and()There is a little difference, If the parameter is not an object, it will be thrown wrong; var empty = {}; (empty); // === true // The object after executing preventExtensions can be modified;(empty); (empty); // === false (1); // TypeError: 1 is not an object (1); //No error will be thrown, will return: ()methodandget是差不多of; var obj = {}; (obj, "prop", "value"); // Output: true( ); // Output: "value"var arr = ["duck", "duck", "duck"]; (arr, 2, "goose"); // true ( arr[2] ); // "goose" (arr, "length", 1); // true ( arr );// ["duck"];(obj) is equivalent to (obj, undefined, undefined);var obj = {}; (obj); // Output: true//The above code is equivalent to (obj, undefined, undefined);(obj, "undefined"); // { value: undefined, writable: true, enumerable: true, configurable: true } There can also be a fourth parameter, which will be used as this of stter;var obj = { value : 10, set key( value ) { ("setter"); = value; }, get key() { return ; } }; (obj,"key","heheda", obj); (obj);() ()methodand差不多一样样of, Will set prototypes for the object, 就是更改对象of__proto__Properties…; ({}, ); // Output true// Give the object array [[Prototype]] to null.({}, null); // true // At this time, obj.__proto__ is undefined//Reset [[prototype]](({}), null); // false // If the prototype chain relies on cyclic dependencies, it will return false.var target = {}; var proto = (target); (target, proto); // false