【问题标题】:Working with Objects in Javascript在 Javascript 中使用对象
【发布时间】: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


【解决方案1】:

这是@Marc B 和@Ray Toal 提到的内容的扩展... 您已经创建了 javascript 函数——这并没有那么糟糕——但不是 JSON。要创建图形,您可以使用画布标签作为“绘图 div”,并​​使用对象的 x 和 y 位置不断更新它们 - 如果您正在考虑制作 2d 动画。如果是这样,我会推荐 CreateJs 作为硬编码 JAVASCRIPT 动画之前的起点。同样,你的代码很好,但是让用户创建这些数据 - 如果你正在考虑使用真正的 JSON 或 Node.js 的服务器应用程序 - 但现在我将专注于单人游戏方面并设置你'是图形'界面'上的对象,例如<canvas>

【讨论】:

  • 您好,感谢您的输入,三角形只是测试数据,不需要动画,也不需要画布。它只是问题,将有预定义的 html 表(数据将在 json 中),然后用户将能够添加一个 html 表等等。但是用户创建的表和预定义的表都需要具有相同的方法。那么最干净的方法是什么?循环遍历数据并为每个对象创建一个对象?还是?..
  • 是的,只要确保您可以使用数组或其他方式访问不同的表。
  • 好的,非常感谢...所有我想知道的,从今天开始我将永远不会使用 json 这个词,除非它的 json...再次感谢大家...
猜你喜欢
  • 1970-01-01
  • 2014-12-18
  • 2023-03-03
  • 1970-01-01
  • 2015-07-19
  • 2019-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多