Javascript 初始化变量用括号括起来的变量声明
Javascript variable declaration with brackets around initialized variables
在React native网站中,有如下一行代码:
var React = require('react-native');
var { TabBarIOS, NavigatorIOS } = React;
例子的第二行,TabBarIOS和NavigatorIOS变量两边的括号是什么意思?
这称为解构赋值。这是 ECMAScript 6 规范中引入的新功能。
这是一个示例对象:
var test = {
"hello": 1,
"world": 2
}
如果我们这样解构它:
var {hello, world} = test;
这相当于做:
var hello = test.hello,
world = test.world;
但是,您可以通过解构赋值做更多有趣的事情...
假设我们有这个对象:
var bucket = {
ExampleObject: function(input){
this.input = input.trim();
return this.input;
},
TestingObject: function(example){
this.example = example || {};
console.log(this.example.input);
}
}
为了记录,我给成员取了讨厌的名字...所以在解构时,我们可以这样重命名它们:
var {ExampleObject: Example, TestingObject: Test} = bucket;
绑定模式遵循如下语法:
{ObjectMemberName}
// Or
{ObjectMemberName: VariableName}
更多信息可以看ECMAScript 6 specification draft or the MDN documentation
在React native网站中,有如下一行代码:
var React = require('react-native');
var { TabBarIOS, NavigatorIOS } = React;
例子的第二行,TabBarIOS和NavigatorIOS变量两边的括号是什么意思?
这称为解构赋值。这是 ECMAScript 6 规范中引入的新功能。
这是一个示例对象:
var test = {
"hello": 1,
"world": 2
}
如果我们这样解构它:
var {hello, world} = test;
这相当于做:
var hello = test.hello,
world = test.world;
但是,您可以通过解构赋值做更多有趣的事情...
假设我们有这个对象:
var bucket = {
ExampleObject: function(input){
this.input = input.trim();
return this.input;
},
TestingObject: function(example){
this.example = example || {};
console.log(this.example.input);
}
}
为了记录,我给成员取了讨厌的名字...所以在解构时,我们可以这样重命名它们:
var {ExampleObject: Example, TestingObject: Test} = bucket;
绑定模式遵循如下语法:
{ObjectMemberName}
// Or
{ObjectMemberName: VariableName}
更多信息可以看ECMAScript 6 specification draft or the MDN documentation