【发布时间】:2014-02-16 21:08:52
【问题描述】:
我目前正在尝试以一种更清晰的面向对象的方式使用 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 仅用于编码数据结构。它不适用于使用其方法对整个对象进行编码。例如它不是“序列化”类型的系统。
-
仅供参考,变量
testJSON的值是不是 JSON。如果它是特定语法的字符串,则只能是 JSON。你所拥有的只是 JavaScript,而不是 JSON。常见的错误。所以,所以,常见的...... -
testJSON甚至不是 JSON。例如,{a: "b"}不是 JSON,而"{'a':'b'}"是。 -
Marc B,我明白,对不起,我明白我的问题可能被误解了。我的意思是我要问的基本上是循环遍历 json 数据并从每个或?. . .对不起,我将修复并修改问题。
标签: javascript oop object