2013-05-14 70 views
1

我有此代码对图像当对象定义中的/这些函数未定义时,代码如何调用对象的函数?

var img = { 
    id: id++, 
    link: m.attr("index"), 
    x: m.offsetx(), 
    y: m.offsety(), 
    width: m.width(), 
    height: m.height() 
}; 

现在我想调用一个函数img.setCordinates(x,y)img.setDimention(w,h),但我不想将它们添加到img对象,我会有很多img对象,他们将保存并加载到文件中。它不是什么功能,我只是想知道它们是如何实现的?

我还要提到这一点,我需要做的这些功能的原因是becouse此代码示例问题:(不好)

arr.getById(index).x = 100; 
arr.getById(index).y = 200; 

.getById()是循环真正的ARR数组的直接原型并查找指定的ID。

回答

7

你应该开始一个新的原型链这样的:

function MyImage(data) 
{ 
    // copy data into this instance 
    for (var key in data) { 
     this[key] = data[key]; // assume that data is anonymous object 
    } 
} 

MyImage.prototype.setCoordinates = function(x, y) { 
    this.x = x; 
    this.y = y; 
} 

MyImage.prototype.setDimensions = function(width, height) { 
    this.width = width; 
    this.height = height; 
} 
// etc. 

然后,您可以创建这样一个新的形象:

var img = new MyImage({ 
    id: id++, 
    link: m.attr("index"), 
    x: m.offsetx(), 
    y: m.offsety(), 
    width: m.width(), 
    height: m.height() 
}); 

img.setCoordinates(0, 0); 

更新

看来,如果我使用JSON.stringify(MyImage的arr),它在加载时不起作用。

这是因为JSON序列化数据,而不是方法或函数。如果你想恢复MyImage对象的数组,你应该这样做:

var images = JSON.parse(data).map(function(image) { 
    return new MyImage(image); 
}); 

匿名函数解析数据映射到一个MyImage对象,并且将其应用于复活的阵列中的每个元素。

+0

这可能是正确的,我可以; t存储该对象,因为当我重新加载它只是一个常规的Object(); .set存储时,还会将.setCoordinates函数附加到每个对象上吗? – Kivylius 2013-05-14 13:49:18

+2

@Jessica我不确定你的意思。你能否详细说明你如何存储对象? – 2013-05-14 14:22:09

+0

你是什么意思“它只是一个普通的对象()”?你有没有试过这个代码?这是一个很好的解决方案。 – chrisvillanueva 2013-05-14 14:23:28

0

如果我明白你想要做什么,只有在对象被实例化或创建时,这会添加你在每个对象上请求的函数。

img.prototype.setCoordinates = function(x, y) { 
    this.x = x; 
    this.y = y; 
} 

img.prototype.setDimension = function(w, h) { 
    this.width = w; 
    this.height = h; 
} 

这是一种节省一些内存空间的方法。这可以工作。

0

据我所知,没有办法按照您的定义实施img.setCoordinates(x,y)img.setDimension(w,h)。 “img”是一个对象。添加“img”。任何东西都会将它添加到img对象中。如果你不想添加内部方法到“img”对象,为什么你不这样做:

setCoordinates(img.x, img.y){ do your stuff in here} 

setDimension(img.width, img.height){ do more stuff here} 
+0

我已经更新了答案。 – Kivylius 2013-05-14 13:56:10

相关问题