使用构造函数的参数值

时间:2016-11-19 03:39:14

标签: javascript html constructor javascript-objects

因此,使用我的代码的以下部分,我一直试图找到对象的名称("对象的名称"指foo,bar,baz,如果这是不正确的术语,请注意,如果使用构造函数的值,则无法在Web上找到任何类似这样的示例。举个例子:

function myFunction(){
  foo = new component(50, 50, "first", "red");
  bar = new component(50, 100, "sec", "red");
  baz = new component(0, 50, "third", "blue");
  jar = new component(0, 100, "fourth", "blue");
}
function component(x, y, id, color){
this.x = x;
this.y = y;
this.id = id;
this.color = color;
}

因此,如果我分别得到x和y,50和100的值,我将使用什么方法来使它成为程序将识别具有这些值的构造函数为bar?如果使用两个值这样做是不可能的,只使用一个值就完全没问题,因为我总是可以将两者合二为一。到目前为止,我能够提出的最好的事情是,那些有用的东西是" foo instanceof component"是的,也许有一些方法我还没发现它基本上与实例相反?提前谢谢。

2 个答案:

答案 0 :(得分:3)

在代码foo中,barbazjar是变量,而不是构造函数。这些变量指向使用component函数作为构造函数创建的对象。

听起来你正在尝试做的是找到使用x和y的特定值创建的对象。一种方法是使用一个查找表,其中键是x和y的组合,值是对象:

var objects = {};
function component(x, y, id, color) {
    this.x = x;
    this.y = y;
    this.id = id;
    this.color = color;

    // Insert the current object into the lookup table
    objects[x + '_' + y] = this;
}

// Retreive an object from the lookup table
function findObject(x, y) {
    return objects[x + '_' + y];
}

这种方法的一个问题是,如果您创建具有相同x和y值的两个对象,则只有最后一个对象将存储在查找表中。你可以通过为每个键存储一个对象数组来解决这个问题。

答案 1 :(得分:0)

使用Nico的代码和Jaromanda X的自包含代码,我能够更新对象以允许用户找到密钥(或者它是可变的,我还是一个根据新的x和y值,不确定,不管是什么" foo")。使用

function myFunction(){
  foo = new component(50, 50, "first", "red");
  bar = new component(50, 100, "sec", "red");
  baz = new component(0, 50, "third", "blue");
  jar = new component(0, 100, "fourth", "blue");
}
var component=(function(){
  var component=function(x, y, id, color){
    this.x = x;
    this.y = y;
    this.id = id;
    this.color = color;
    objects[x+'_'+y] = this;
    this.newPos = function(x, y){
      this.x = x;
      this.y = y;
      //objects[this.x+"_"+this.y] = this;
    };
  };
  component.get = function(x, y){
    return objects[x+'_'+y];
  };
  return component
})();

' this.newPos'会改变这个' x和y,取决于它的参数是什么,但仅这将迫使用户继续使用键/变量的原始x和y值,正如RobG指出的那样。要解决此问题,只需删除newPos中的注释即可。代码将使对象' x和y值是什么' this.x'和' this.y'在newPos中,这将是新的价值。