ES6は、オブジェクトプロパティおよびメソッドとして、被験体に直接描画変数および関数を可能にします。この方法では、オブジェクトの定義を簡素化します。
プロパティの簡潔な表現
1.基本的な定義
-
プロパティとメソッドの簡潔な表現
//一 属性的简洁表示 const foo = 'bar'; const baz = {foo}; baz // {foo: "bar"} // 等同于 const baz = {foo: foo}; //二 方法的简洁表示 const o = { method() { return "Hello!"; } }; // 等同于 const o = { method: function() { return "Hello!"; } };
2.オブジェクトのプロパティと速記例を使用する方法
-
①オブジェクトのプロパティ速記使用例
function f(x, y) { return {x, y}; } // 等同于 function f(x, y) { return {x: x, y: y}; } f(1, 2) // Object {x: 1, y: 2}
-
②オブジェクトのプロパティと速記例を使用する方法
let birth = '2000/01/01'; const Person = { name: '张三', //等同于birth: birth birth, // 等同于hello: function ()... hello() { console.log('我的名字是', this.name); } };
-
③速記プロパティは、簡単な関数は値を戻します
function getPoint() { const x = 1; const y = 10; return {x, y}; } getPoint() // {x:1, y:10}
-
速記法属性を使用して変数の④CommonJSモジュール出力セット。
let ms = {}; function getItem (key) { return key in ms ? ms[key] : null; } function setItem (key, value) { ms[key] = value; } function clear () { ms = {}; } module.exports = { getItem, setItem, clear }; // 等同于 module.exports = { getItem: getItem(key), setItem: setItem(key,value), clear: clear() };
-
評価者⑤プロパティ(設定器)と値(ゲッタ)であり、また、速記の方法を使用
const cart = { _wheels: 4, get wheels () { return this._wheels; }, set wheels (value) { if (value < this._wheels) { throw new Error('数值太小了!'); } this._wheels = value; } }
-
⑥オブジェクトを印刷する簡単な方法を使用します
let user = { name: 'test' }; let foo = { bar: 'baz' }; console.log(user, foo) // {name: "test"} {bar: "baz"} console.log({user, foo}) // {user: {name: "test"}, foo: {bar: "baz"}}