현재 클리너 개체 지향적 인 방식으로 JavaScript로 작업하려고합니다. 이렇게 완전히 잘못하고있는 경우 실례합니다. this 이전 질문은 일반적인 참조로 대답하지만 ,자바 스크립트에서 개체 작업
//Create some sample objects to play with.
var testJSON = {
"rectangle": [
{ "id":3 , "x":5, "y":10, "width":10, "height":50
}
]
};
//Create Rectangle Constructor
var rectangle = {
init: function(i, x, y, width, height) {
this.id = i,
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.fields = []
},
move: function(x, y) {
this.x += x;
this.y += y;
}
};
//Create test array to hold all the objects
var test = [];
//Create a new rectangle object
var myRectangle = Object.create(rectangle);
myRectangle.init(1, 0, 0, 2, 4);
myRectangle.move(3, 5);
//put rectangle object in array associated with id
test[myRectangle.id] = myRectangle;
//Create a new rectangle object with the same variable name as it will all be in an array anyway.
var myRectangle = Object.create(rectangle);
myRectangle.init(2, 0, 0, 2, 4);
myRectangle.move(0, 0);
//put rectangle object in array associated with id
test[myRectangle.id] = myRectangle;
//put JSON result in
test[testJSON.rectangle[0].id] = testJSON.rectangle[0];
//No Longer need this variable, is it worth getting rid of.. i dont know
myRectangle =null;
//Try and use methods created in the constructor.
test[2].move(4,8);
console.log(test);
좋아, 이제 실제 질문, 내가 만들려고하고 응용 프로그램을 모두 JSON 데이터를 가지고 있으며, 예를 들어, 그래서 그것은 데이터를 생성 사용자가있을 것입니다 : 여기 내 '테스트'코드의 응용 프로그램이 생성됩니다 한 묶음의 '직사각형'을 만들고 사용자는 또한 직사각형을 만들 수 있습니다. 그래서 첫 번째 질문은 '올바른 접근인가?'이고 두 번째로 json 데이터에 사각형 생성자 (이동)에 정의 된 메서드가있는 방법은 무엇입니까?
도움을 주시면 감사하겠습니다.
json은 데이터 구조를 인코딩하기위한 것입니다. 그것들은 메소드를 사용하여 전체 객체를 인코딩하기위한 것이 아닙니다. 예 : 그것은 "직렬화"형 시스템이 아닙니다. –
그냥 FYI, 변수'testJSON'의 값은 _not_ JSON입니다. 특정 구문의 문자열 인 경우에만 JSON이 될 수 있습니다. 가지고있는 것은 JSON이 아니라 단지 JavaScript입니다. 일반적인 실수. 그래서, 공통점은 ... –
'testJSON'은 JSON이 아닙니다. 예를 들어'{a : "b"}'는 JSON이 아니고' "{ 'a': 'b'}"'는 JSON이 아닙니다. –