5. 객체의 확장

3142 단어

속성과 방법의 간결한 표현법

var birth = '2000/01/01';
var Person = { 
   name: ' ', 
   // birth: birth 
   birth,  
   //  hello: function ()...
   hello() { console.log(' ', this.name); }
};

// 
function getPoint() {
   var x = 1; var y = 10; 
   return {x, y};
}
getPoint()
// {x:1, y:10}

//commonjs 
module.exports = { getItem, setItem, clear };
//  
module.exports = {
 getItem: getItem, 
 setItem: setItem, 
clear: clear
};

//get set 
var cart = { 
  _wheels: 4, 
  get wheels () { return this._wheels; }, 
  set wheels (value) {
    if (value < this._wheels) {
      throw new Error(' !'); 
     }
   this._wheels = value; 
  }
}

속성 표현()

var lastWord = 'last word';
var a = {
 'first word': 'hello', 
[lastWord]: 'world'};
a['first word'] // "hello"
a[lastWord] // "world"
// 
a['last word'] // "world"

Object.is()


두 값이 동일한지 비교하는 데 사용
+0 === -0 //true
NaN === NaN // false
Object.is(+0, -0) // false
Object.is(NaN, NaN) // true

스스로 실현하면 다음과 같은 코드를 채택할 수 있다
Object.defineProperty(Object, 'is', { 
  value: function(x, y) {
   if (x === y) {  
  //  +0   -0  
    return x !== 0 || 1 / x === 1 / y; 
  }  
  //  NaN 
  return x !== x && y !== y;
 }, 
   configurable: true, 
   enumerable: false,
   writable: true}
);

Object.assign()


대상의 합병에 사용되며 원본 대상 (source) 의 모든 열거 가능한 속성을 대상 대상 (target) 으로 복사합니다.대상 객체가 소스 객체와 같은 이름의 속성이 있거나 여러 소스 객체에 같은 이름이 있으면 뒤의 속성이 앞의 속성을 덮어씁니다.
var target = { a: 1, b: 1 };
var source1 = { b: 2, c: 2 };
var source2 = { c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}

매개 변수가 객체가 아니면 먼저 객체로 전환한 다음 로 돌아갑니다.
typeof Object.assign(2)

Object.assign 복사의 속성은 제한이 있습니다. 원본 대상의 자체 속성만 복사합니다. (계승 속성은 복사하지 않습니다.) 일일이 열거할 수 없는 속성도 복사하지 않습니다. (enumerable:false)
일반적인 용도:
  • 객체에 속성 추가
  • class Point { 
        constructor(x, y) { 
          Object.assign(this, {x, y}); 
        }
    }
    
  • 을 대상으로 추가하는 방법
  • Object.assign(SomeClass.prototype, { 
      someMethod(arg1, arg2) { ··· },
       anotherMethod() { ··· }
    });
    //  
    SomeClass.prototype.someMethod = function (arg1, arg2) { ···};
    SomeClass.prototype.anotherMethod = function () { ···};
    
  • 클론 개체
  • function clone(origin) { return Object.assign({}, origin);}
    

    이런 방법으로 복제하면 원시 대상의 값만 복제할 수 있고 상속된 값은 복제할 수 없다.계승 체인을 유지하려면 아래 코드를 사용하세요.
    function clone(origin) {
       let originProto = Object.getPrototypeOf(origin);
       return Object.assign(Object.create(originProto), origin);
    }
    
  • 여러 객체 결합
  • const merge = (target, ...sources) => Object.assign(target, ...sources);
    
  • 속성에 대한 기본값 지정
  • const DEFAULTS = { logLevel: 0, outputFormat: 'html'};
    function processContent(options) { 
          options = Object.assign({}, DEFAULTS, options);
    }
    

    좋은 웹페이지 즐겨찾기