[javascript] 자바 스크립트 개체 속성의 기본값 설정

다음과 같이 javascript 객체의 기본 속성을 설정하는 방법이 있습니까?

var emptyObj = {};
// do some magic
emptyObj.nonExistingAttribute // => defaultValue

IE는 무시할 수 있습니다. Chrome 프레임은 그 두통을 덜어주었습니다.



답변

몇 년 전에 질문 한 이후로 상황이 잘 진행되었습니다.

프록시는 ES6의 일부입니다. 다음 예제는 Chrome, Firefox, Safari 및 Edge 에서 작동합니다 .

var handler = {
  get: function(target, name) {
    return target.hasOwnProperty(name) ? target[name] : 42;
  }
};

var p = new Proxy({}, handler);

p.answerToTheUltimateQuestionOfLife; //=> 42

Mozilla의 Proxies 문서에서 더 많은 것을 읽으십시오 .


답변

자바 스크립트에서이를 설정하는 방법은 없습니다. undefined존재하지 않는 속성을 반환 하는 것은 핵심 자바 스크립트 사양의 일부입니다. 이 유사한 질문에 대한 토론을 참조하십시오 . 내가 거기에서 제안했듯이 한 가지 접근 방식 (정말 추천 할 수는 없지만)은 전역 getProperty함수 를 정의하는 것입니다 .

function getProperty(o, prop) {
    if (o[prop] !== undefined) return o[prop];
    else return "my default";
}

var o = {
    foo: 1
};

getProperty(o, 'foo'); // 1
getProperty(o, 'bar'); // "my default"

그러나 이것은 다른 사람들이 읽기 어려운 비표준 코드로 이어질 것이며 정의되지 않은 값을 기대하거나 원하는 영역에서 의도하지 않은 결과를 초래할 수 있습니다. 이동하면서 확인하는 것이 좋습니다.

var someVar = o.someVar || "my default";


답변

사용 destructuring (새 ES6에서)

Mozila의 훌륭한 문서 와 구문을 내가 할 수있는 것보다 더 잘 설명 하는 환상적인 블로그 게시물 이 있습니다.

질문에 답하려면

var emptyObj = {};
const { nonExistingAttribute = defaultValue } = emptyObj;
console.log(nonExistingAttribute); // defaultValue

더 나아 가기

이 변수의 이름을 바꿀 수 있습니까 ? 확실한!

const { nonExistingAttribute: coolerName = 15} = emptyObj;
console.log(coolerName); // 15

중첩 된 데이터는 어떻습니까? 가져와!

var nestedData = {
    name: 'Awesome Programmer',
    languages: [
        {
            name: 'javascript',
            proficiency: 4,
        }
    ],
    country: 'Canada',
};

var {name: realName, languages: [{name: languageName}]} = nestedData ;

console.log(realName); // Awesome Programmer
console.log(languageName); // javascript


답변

이것은 확실히 프로토 타입 기반 개체의 일반적인 사용처럼 들립니다.

// define a new type of object
var foo = function() {};

// define a default attribute and value that all objects of this type will have
foo.prototype.attribute1 = "defaultValue1";

// create a new object of my type
var emptyObj = new foo();
console.log(emptyObj.attribute1);       // outputs defaultValue1


답변

내 코드는 다음과 같습니다.

function(s){
    s = {
        top: s.top || 100,    // default value or s.top
        left: s.left || 300,  // default value or s.left
    }
    alert(s.top)
}


답변

이것을 달성하는 방법은 object.assign기능입니다.

const defaultProperties = { 'foo': 'bar', 'bar': 'foo' };
const overwriteProperties = { 'foo': 'foo' };
const newObj = Object.assign({}, defaultProperties, overwriteProperties);
console.log(defaultProperties);  // {"foo": "bar", "bar": "foo"}
console.log(overwriteProperties);  // { "foo": "foo" };
console.log(newObj);  // { "foo": "foo", "bar": "foo" }


답변

가장 간단한 접근 방식은 Object.assign.

이 클래스가있는 경우 :

class MyHelper {
    constructor(options) {
        this.options = Object.assign({
            name: "John",
            surname: "Doe",
            birthDate: "1980-08-08"
        }, options);
    }
}

다음과 같이 사용할 수 있습니다.

let helper = new MyHelper({ name: "Mark" });
console.log(helper.options.surname); // this will output "Doe"

문서 (폴리 필 포함) :
https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/assign