Javascript 객체는 어떻게 그 자체의 값을 참조 할 수 있습니까? [복제]
이 질문에는 이미 답변이 있습니다.
- 객체 리터럴 / 이니셜 라이저의 자체 참조 22 답변
다음 자바 스크립트가 있다고 가정 해 보겠습니다.
var obj = {
key1 : "it ",
key2 : key1 + " works!"
};
alert(obj.key2);
"key1이 정의되지 않았습니다"와 함께이 오류가 발생했습니다. 나는 시도했다
this.key1
this[key1]
obj.key1
obj[key1]
this["key1"]
obj["key1"]
그리고 그들은 결코 정의되지 않은 것 같습니다.
key2가 key1의 값을 참조하도록하려면 어떻게해야합니까?
어쩌면 함수에서 속성을 제거하는 것에 대해 생각할 수 있습니다. 나는 이와 같은 것을 의미한다 :
var obj = {
key1: "it ",
key2: function() {
return this.key1 + " works!";
}
};
alert(obj.key2());
리터럴 대신 생성자 함수를 사용하면됩니다.
var o = new function() {
this.foo = "it";
this.bar = this.foo + " works"
}
alert(o.bar)
해당 객체를 초기화하기 전에는 객체의 속성을 참조 할 수 없습니다. 외부 변수를 사용하십시오.
var key1 = "it";
var obj = {
key1 : key1,
key2 : key1 + " works!"
};
또한 이것은 "JSON 객체"가 아닙니다. Javascript 객체입니다. JSON은 문자열 (유효한 Javascript 코드 임)로 객체를 나타내는 방법입니다.
한 가지 대안은 getter / setter 메소드를 사용하는 것입니다.
예를 들어 계산 된 값을 읽는 것에 만 관심이있는 경우 :
var book = {}
Object.defineProperties(book,{
key1: { value: "it", enumerable: true },
key2: {
enumerable: true,
get: function(){
return this.key1 + " works!";
}
}
});
console.log(book.key2); //prints "it works!"
그러나 위의 코드는 key2에 대한 다른 값을 정의 할 수 없습니다.
따라서 key2의 값을 재정의하려는 경우 상황이 조금 더 복잡해집니다. 항상 계산 된 값이됩니다. 아마도 그것은 당신이 원하는 것입니다.
그러나 key2의 값을 재정의하려면 계산과는 별도로 해당 값을 캐시 할 수있는 공간이 필요합니다.
이 같은 것 :
var book = { _key2: " works!" }
Object.defineProperties(book,{
key1: { value: "it", enumerable: true},
_key2: { enumerable: false},
key2: {
enumerable: true,
get: function(){
return this.key1 + this._key2;
},
set: function(newValue){
this._key2 = newValue;
}
}
});
console.log(book.key2); //it works!
book.key2 = " doesn't work!";
console.log(book.key2); //it doesn't work!
for(var key in book){
//prints both key1 and key2, but not _key2
console.log(key + ":" + book[key]);
}
또 다른 흥미로운 대안은 자체 초기화 객체를 사용하는 것입니다.
var obj = ({
x: "it",
init: function(){
this.y = this.x + " works!";
return this;
}
}).init();
console.log(obj.y); //it works!
명령문 정의 obj
가 완료 key1
되지 않았으므로 아직 존재하지 않습니다. 이 솔루션을 고려하십시오.
var obj = { key1: "it" };
obj.key2 = obj.key1 + ' ' + 'works!';
// obj.key2 is now 'it works!'
That's not a JSON object, that's a Javascript object created via object literal notation. (JSON is a textual notation for data exchange (more). If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON.)
There's no way within the object initializer to refer to another key of the object being initialized, because there's no way to get a reference to the object being created until the initializer is finished. (There's no keyword akin to this
or something for this situation.)
You can also reference the obj
once you are inside the function instead of this
.
var obj = {
key1: "it",
key2: function(){return obj.key1 + " works!"}
};
alert(obj.key2());
This is not JSON. JSON was designed to be simple; allowing arbitrary expressions is not simple.
In full JavaScript, I don't think you can do this directly. You cannot refer to this
until the object called obj
is fully constructed. So you need a workaround, that someone with more JavaScript-fu than I will provide.
참고URL : https://stackoverflow.com/questions/2787245/how-can-a-javascript-object-refer-to-values-in-itself
'IT' 카테고리의 다른 글
PowerShell에서 배열 객체를 문자열로 어떻게 변환합니까? (0) | 2020.06.09 |
---|---|
저장소에서 업데이트 된 종속성을 확인한 Maven (0) | 2020.06.09 |
PostgreSQL에서 평균을 소수점 이하 2 자리로 반올림하는 방법은 무엇입니까? (0) | 2020.06.09 |
정규식을 사용하여 문자를 대문자로 변환 (EditPad Pro) (0) | 2020.06.09 |
jQuery UI 대화 상자가 첫 번째 텍스트 상자에 초점을 설정하지 못하게하십시오. (0) | 2020.06.09 |