ES6 객체 속성 이름 단순화 표현 및 표현식, 객체 새 메서드, 속성 반복
                                            
 9407 단어  javascriptes6
                    
개관  
객체 속성의 간결한 표현
  
ES6에서는 변수와 함수를 객체의 속성과 방법으로 직접 쓸 수 있습니다.
ES6에서는 객체에 속성 이름만 쓰고 속성 값은 쓰지 않을 수 있습니다.let foo = 'bar';
let baz = {foo};
console.log(baz); // {foo:'bar'}
// same as
let baz1 = {foo:foo}
console.log(baz1); // {foo:'bar'}
let first = 'Jone';
let last = 'Doe';
let obj = {first,last};
console.log(obj); // {first: "Jone", last: "Doe"}
// same as
let obj1 = {first:first,last:last};
console.log(obj1); // {first: "Jone", last: "Doe"}
const HELLO = {
  method(){
    return 'hello'
  }
}
console.log(HELLO.method()); // 'hello'
// same as
const HELLO1 = {
  method:function(){
    return 'hello'
  }
}
console.log(HELLO1.method()); // 'hello'
  
실제 활용 사례://             
let birth = '2000/01/01'
const PERSON = {
  name: '  ',
  birth, // same as: birth:birth
  hello() {console.log('     ', this.name);}
  // same as: hello:function(){...}
}
//        
function getPoint(x = 1, y=10){
  return {x, y}
}
console.log(getPoint()); // {x: 1, y: 10}
console.log(getPoint(3,3)); // {x: 3, y: 3}
console.log(getPoint(3)); // {x: 3, 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};
// same as: module.exports = {getItem:getItem,setItem:setItem,clear:clear};
//           
const CART = {
  _wheels: 4,
  get wheels(){
    return this._wheels;
  },
  set wheels(value){
    if(value
  
속성 이름 표현식
  
ES6는 글자 크기로 대상을 정의할 때 표현식을 대상의 속성 이름으로 사용한다. 즉, 표현식을 네모난 괄호 안에 놓는다.
객체 속성을 정의하는 두 가지 방법:
let foo = 'bar';
let baz = {foo};
console.log(baz); // {foo:'bar'}
// same as
let baz1 = {foo:foo}
console.log(baz1); // {foo:'bar'}
let first = 'Jone';
let last = 'Doe';
let obj = {first,last};
console.log(obj); // {first: "Jone", last: "Doe"}
// same as
let obj1 = {first:first,last:last};
console.log(obj1); // {first: "Jone", last: "Doe"}
const HELLO = {
  method(){
    return 'hello'
  }
}
console.log(HELLO.method()); // 'hello'
// same as
const HELLO1 = {
  method:function(){
    return 'hello'
  }
}
console.log(HELLO1.method()); // 'hello'//             
let birth = '2000/01/01'
const PERSON = {
  name: '  ',
  birth, // same as: birth:birth
  hello() {console.log('     ', this.name);}
  // same as: hello:function(){...}
}
//        
function getPoint(x = 1, y=10){
  return {x, y}
}
console.log(getPoint()); // {x: 1, y: 10}
console.log(getPoint(3,3)); // {x: 3, y: 3}
console.log(getPoint(3)); // {x: 3, 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};
// same as: module.exports = {getItem:getItem,setItem:setItem,clear:clear};
//           
const CART = {
  _wheels: 4,
  get wheels(){
    return this._wheels;
  },
  set wheels(value){
    if(valuelet obj = {};
obj.foo = true;
console.log(obj); // {foo: true}let obj1 = {};
obj1['a'+'bc'] = 123;
console.log(obj1); // {abc: 123}let propKey = 'foo';
let propKeyObj = {
  [propKey]: true,
  ['a'+ 'bc']: 123
}
console.log(propKeyObj); // {foo: true, abc: 123}
let lastWord = 'last word';
let a = {
  'first word':'hello',
  [lastWord]:'world'
}
console.log(a); // {first word: "hello", last word: "world"}
console.log(a['first word']);// 'hello'
console.log(a[lastWord]); // 'world'
console.log(a['last word']); // 'world'
//      
let methodName = {
  ['h'+'ello'](){
    return 'hi'
  }
}
console.log(methodName.hello()); // 'hi'참고: 속성 이름 표현식은 단순 표현식과 함께 사용할 수 없습니다.
//   
let foo = 'bar';
let bar = 'abc';
let baz = {[foo]};주의: 속성 표현식이 대상이라면 기본적으로 대상을 문자열
[object Object]으로 바꿉니다const keyA = {a:1};
const keyB = {b:2};
const myObject = {
  [keyA]: 'valueA',
  [keyB]: 'valueB',
}
console.log(myObject); // {[object Object]: "valueB"}Object.is(value1,value2)
엄격한 연산자(===)와 같은 행위는 기본적으로 일치한다.
엄격한 연산자 해결(==)
NaN은 자신과 같지 않고 +0은-0의 문제입니다.console.log(Object.is('foo','foo'));; // true
console.log({} === {}); // false
console.log(Object.is({},{})); // false
console.log(NaN === NaN); // false
console.log(Object.is(NaN,NaN)); // true
console.log(+0 === -0); // true
console.log(Object.is(+0,-0)); // false
console.log([0,NaN,2].indexOf(NaN)); // -1
console.log([0,NaN,2].findIndex(x => Object.is(x, NaN))); // 1Object.assign(target,source_1,source_2,...)
Object.assign() 방법은 원본 대상(source)의 모든 열거 가능한 속성을 목표 대상(target)에 통합시킨다. 이것은 target을 수정하고 우선source1의 모든 열거 가능한 자신의 속성을 target에 복사한 다음source2의 모든 속성을 target에 복사합니다.마지막으로 target을 되돌려줍니다.let target = {a:1};
let source_1 = {b:2};
let source_2 = {c:3};
Object.assign(target,source_1,source_2);
console.log(target,source_1,source_2); // {a: 1, b: 2, c: 3} {b: 2} {c: 3}Object.assign()이 어떻게 작동하는지 자세히 살펴보겠습니다.String, Symbel을 속성 키로 지원한다.let v1 = 'abc';
let v2 = true;
let v3 = 10;
let v4 = {[Symbol('c')]: 'c'};
const obj = Object.assign({}, v1, v2, v3, v4);
console.log(obj); // {0: "a", 1: "b", 2: "c", Symbol(c): "c"}const obj = Object.assign({b: 'c'},
    Object.defineProperty({}, 'invisible',{
      enumerable:false, // enumerable    ‘    ’
      value:'hello'
    })
)
console.log(obj); // {b: "c"}target이 setter을 보유하고 있다면 복제 기간에 이 setter을 호출한다는 뜻이다.다른 방법은 새로운 속성을 정의하는 것이다. 이것은 항상 새로운 자신의 속성을 만들고 setter을 호출하지 않는 작업이다.처음에 어떤 사람들은 Object.assign()의 변체를 사용하자고 제안했는데, 이것은 값을 부여하는 방식이 아니라 정의를 사용한다.이 제안은 ECMAScript 6에서 거부되었으나 이후 릴리즈에서는 재검토될 수 있습니다.let obj1 = {a: {b: 1}};
let obj2 = Object.assign({}, obj1);
console.log(obj2); // {a: {b: 1}} //Object.assign () 방법은 깊이 있는 복제가 아니라 얕은 복제입니다.let target = {a: { b: 'c', d: 'e' }};let source = {a: { b: 'hello' }};const obj = Object.assign(target, source);console.log(obj);//a: {b: "hello"}console.log(target);//a: {b: "hello"}
    :  
**       **  class Point{ constructor(x, y){
Object.assign(this, {x, y});}}
**       **  function SomeClass(){
}Object.assign(SomeClass.prototype, { someMethod(arg1,arg2){
// ...}, anotherMethod(){
// ...}})console.dir(SomeClass);
//same asSomeClass.prototype.someMethod = function(arg1, arg2){//...};SomeClass.prototype.anotherMethod = function(){//...}
**    **  //원시 대상 자체의 값을 복제하는 function clone1(origin) {return Object.assign({},origin);
//원본 객체 상속 복제의 값(상속 체인 유지)function clone2(params) {let params Proto = Object.get Proto typeOf(params), return Object.assigin(Object.create(params Proto), params)}
**      **//여러 객체가 targetconst merge1 = (target,...sources) = > Object에 결합됩니다.assign(target, ...sources);//다중 객체 병합이 새 객체 const merge2 = (...sources) => Object를 반환합니다.assign({}, ...sources);
**        **  const DEFAULTS = { logLevel: 0, output: 'html'};function processContent(options){ options = Object.assign({},DEFAULTS,options); console.log(options);}processContent('abc');//{0: "a", 1: "b", 2: "c", logLevel: 0, output: "html"}processContent({'abc':'abc'});//{logLevel: 0, output: "html", abc: "abc"}
###        
> `for...in`、`Object.keys(obj)`、`Object.getOwnPropertyNames(obj)`、`Object.getOwnPropertySymbels(obj)`、`Reflect.ownKeys(obj)`  
function allObj () {this.name = '장 3';//자체 속성this.age = '12';//자체 속성this.invisible = {
enumerable: false,
value: 'hello'}, this.invisible = {
enumerable: false,
value: 'hello'}}allObj.prototype.disEnum = { enumerable: false, value: 'disEnum'}allObj.prototype.Enum = { enumerable: true, value: 'Enum'}let obj = new allObjObject.assign(obj, { a: '1', b: '2', c: '3',
})//let obj2 = Object.assign(obj1,//Object.defineProperty({}, )//)Object.assign(obj, Object.defineProperty({}, 'visible',{
enumerable: true,
value: 'word'}))console.log(obj);//allobj {a: "1",age: "12", b: "2", c: "3", invisible: {enumerable: false,value:'hello'},name:'장삼',visible:'word', Symbol(c):'c',proto__:Enum: {enumerable: true, value: "Enum"},disEnum: {enumerable: false, value: "disEnum"}}//for...in이 객체 자체와 상속을 반복하는 속성(Symbol 속성 제외) for(let key in obj) {console.log(key);//name//age//invisible//a//b//c//invisible//visible//disEnum//Enum}
//Object.keys () 는 객체 자체 (상속이 없음) 의 모든 속성 (Symbol 속성이 없음) console을 포함하는 그룹을 되돌려줍니다.log(Object.keys(obj));//["name", "age", "invisible", "a", "b", "c", "visible"]
//Object.getOwnPropertyNames는 객체 자체의 모든 속성을 포함하는 그룹을 반환합니다(Symbol 속성은 포함되지 않지만 열거할 수 없는 속성을 포함합니다)console.log(Object.getOwnPropertyNames(obj));//["name", "age", "invisible", "a", "b", "c", "visible"]
//Object.getOwnPropertySymbols () 는 모든 대상 자체의 모든 Symbol 속성console을 포함하는 그룹을 되돌려줍니다.log(Object.getOwnPropertySymbols(obj));//[Symbol(c)]
//Reflect.ownKeys () 는 객체 자체의 모든 속성을 포함하는 그룹을 되돌려줍니다. 속성 이름이 Symbol이든 문자열이든,console을 열거할 수 있든 상관없습니다.log(Reflect.ownKeys(obj));//["name", "age", "invisible", "a", "b", "c", "visible", Symbol(c)]
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
ES6 객체 속성 이름 단순화 표현 및 표현식, 객체 새 메서드, 속성 반복Object.assign() 방법은 원본 대상(source)의 모든 열거 가능한 속성을 목표 대상(target)에 통합시킨다. 이것은 항상 새로운 자신의 속성을 만들고 setter을 호출하지 않는 작업이다.처음에 어...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.