5. 객체의 확장
속성과 방법의 간결한 표현법
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);
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.