javascript 语法 Optional Chaining
Optional Chaining
在javaScript中,对象的属性链访问,很容易因为某一个属性不存在出现
Cannot read property 'xxx' of undefined的问题,那么Optional Chaining就添加了?.操作符,它会先判断前面的值,如果undefined或者null,就结束后面的调用,直接返回undefined;
1. 访问深度嵌套的属性
const obj = {
foo: {
bar: {
baz: 42,
},
},
};
const baz = obj?.foo?.bar?.baz; // 42
const safe = obj?.qux?.baz; // undefined
// Optional chaining and normal chaining can be intermixed
obj?.foo.bar?.baz; // Only access `foo` if `obj` exists, and `baz` if
// `bar` exists
// Example usage with bracket notation:
obj?.['foo']?.bar?.baz // 42
2.调用深层嵌套的函数
const obj = {
foo: {
bar: {
baz() {
return 42;
},
},
},
};
const baz = obj?.foo?.bar?.baz(); // 42
const safe = obj?.qux?.baz(); // undefined
const safe2 = obj?.foo.bar.qux?.(); // undefined
const willThrow = obj?.foo.bar.qux(); // Error: not a function
// Top function can be called directly, too.
function test() {
return 42;
}
test?.(); // 42
exists?.(); // undefined
3.构造深层嵌套的类
const obj = {
foo: {
bar: {
baz: class {
},
},
},
};
const baz = new obj?.foo?.bar?.baz(); // baz instance
const safe = new obj?.qux?.baz(); // undefined
const safe2 = new obj?.foo.bar.qux?.(); // undefined
const willThrow = new obj?.foo.bar.qux(); // Error: not a constructor
// Top classes can be called directly, too.
class Test {
}
new Test?.(); // test instance
new exists?.(); // undefined
4.安装使用
npm install --save-dev @babel/plugin-proposal-optional-chaining
yarn add @babel/plugin-proposal-optional-chaining --dev
.babelrc
{
"plugins": ["@babel/plugin-proposal-optional-chaining"]
}
javascript|Optional Chaining|Optional Chaining|平易在线