2013-05-14 98 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

相關問題