2014-06-19 2 views
3

ECMAScript5에서 객체를 만드는 두 가지 방법이 있다는 것을 알고 있습니다. (디폴트)은() 기본적으로 false로 모든 데이터 디스크립터 설정 Object.create 방법을 이용 (참 쓰기, 구성, 열거.리터럴 표기법 (객체 생성)의 데이터 설명자

2/모든 내부 데이터 속성을 설정

1/리터 표기.

는 Object.keys이 (obj2보다) 하늘의 배열을 반환해서는 안 object2에이 일을하는 동안은 유효? 리터럴 표기법 false로 열거 설정할 수 있나요?

var obj1 = Object.create(null, { 
    'name': {value: 'first object name'}, 
    'surename': {value: 'first object surname', enumerable: true, configurable: true} 
}); 

var obj2 = {'x': {value: 10, enumerable: false}}; 

console.log(Object.keys(obj1)); // ["surename"] 
console.log(Object.keys(obj2)); // ["x"] 

link

012 JsFiddle

답변

3

너무 위아래로 검색하여 찾을 수 없습니다. 즉,이 같은 당신이 필요로하는 모든, 만약 당신이 그러나 getter 및 setter 함수를 정의 할 수 있습니다 :

var x = { 
    y: 6, 
    get foo() { 
    return this.y + 10; 
    }, 
    set bar(value) { 
    this.y = foo - 1; 
    } 
}; 

x.y; // 6 
x.foo; // 16 
x.bar = 8; 
x.y; // 7 
x.foo; // 17 

가 나는 또한 문자 표기법 정의 특성을 용이하게하기 위해 작은 유틸리티를 정의했다. 여기있다 :

/* 
* Facilitates defining properties with advanced attributes in literal notation. 
* 
* Example: 
* var foo = { 
*  x: 6, 
*  bar: new Property({ 
*  enumerable: false, 
*  get: function() { 
*   return this.x + 1 
*  } 
*  }) 
* } 
* foo.bar // value is an object of type Property 
* Properties.eval(foo) 
* foo.bar // value is now 7 
*/ 

'use strict' 

/** 
* Constructor. 
* 
* @param {object} descriptor 
* the property descriptor, in the format used by <code>Object.defineProperty</code> 
* 
* @returns {Property} 
* 
* @see Object.defineProperty 
*/ 
var Property = function (descriptor) { 
    this.descriptor = descriptor 
    Object.freeze(this) 
} 

Property.prototype.toString = function() { 
    return 'Property' 
} 

var Properties = new Object(null) 

/** 
* Replace all properties of type <code>Property</code> contained in the 
* specified object with the value associated with the <code>Property</code>. 
* 
* @param {object} object 
* the object 
*/ 
Properties.eval = function (object) { 
    // recursive 
    for (var propertyName in object) { 
    if (object.hasOwnProperty(propertyName)) { 
     var property = object[propertyName] 
     if (property instanceof Property) { 
     Object.defineProperty(object, propertyName, property.descriptor) 
     property = object[propertyName] 
     } 
     if (property instanceof Object) { 
     Properties.eval(property) 
     } 
    } 
    } 
} 
2

Essentialy,이 라인 : value과 :

var obj2 = {'x': {value: 10, enumerable: false}}; 

당신이 변수 obj2 선언하는 하나 명의 값이 두 가지 속성을 가진 객체가 재산 x와 객체 enumerable. Object.create()은 단순히 생성되는 객체의 속성을 정의하기 위해 리터럴 표기법을 사용하는 함수입니다.

2

리터럴 표기법에서 열거 형을 false로 설정하는 것이 유효합니까? object2에서이 작업을 수행하는 동안 Object.keys(obj2)은 빈 배열을 반환하지 않아야합니까?

"유효"의 의미에 따라 다릅니다. 정답은 이 아니며 (적어도 ES5에서)이므로 객체를 값으로 갖는 두 개의 속성이있는 객체를 정의하는 것입니다.

그냥 obj.x을 살펴보십시오.