📜  JavaScript Reflect get()方法

📅  最后修改于: 2020-10-25 11:54:43             🧑  作者: Mango

JavaScript Reflect.get()方法

静态Reflect.get()方法用于从对象作为函数检索属性。第一个参数是对象,第二个参数是属性名称。

句法:

Reflect.get(target, propertyKey[, receiver])

参数:

target:这是在其上获取属性的目标对象。

propertyKey:这是要获取的密钥的名称。

接收者:如果遇到吸气剂,则为调用对象提供的值。

返回值:

它返回属性的值。

异常处理:

如果目标不是Object,则为TypeError。

浏览器支持:

Chrome 49
Edge 12
Firefox 42
Opera 36

例子1

const u = {p:3};
console.log( Reflect.get ( u , "p" ) === 3 );
// if property key is not found, return undefined just like obj.key
console.log( Reflect.get ( u , "h" ) === undefined ); 
console.log( Reflect.get ( u , "h" ) === 3 );

输出:

true

true

false

例子2

const x = {p:3};
const y = Object.create (x);
// x is parent of y
console.log (
    Reflect.get ( y, "p" ) === 3
  // Reflect.get will traverse the prototype chain to find property
); 

输出:

true

例子3

const object1 = {
  x: 1,
  y: 2
};
console.log(Reflect.get(object1, 'y'));
// expected output: 1
var array1 = ['zero', 'one','Carry','marry','charry'];
console.log(Reflect.get(array1, 4));

输出:

 2
 "charry"