javascript - How does code call function(s) of objects when that/those function(s) is/are undefined in the object definition? -
i have code image
var img = { id: id++, link: m.attr("index"), x: m.offsetx(), y: m.offsety(), width: m.width(), height: m.height() };
now call function img.setcordinates(x,y)
, img.setdimention(w,h)
, dont want add them img
object have many img
object , saved , loaded in file. not mater function do, i'm wondering how implemented?
i should mention this, reason need these function becouse of code example problem: (not good)
arr.getbyid(index).x = 100; arr.getbyid(index).y = 200;
.getbyid()
direct prototype of array loops true arr , id specified.
you should start new prototype chain this:
function myimage(data) { // copy data instance (var key in data) { this[key] = data[key]; // assume data 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.
then can create new image this:
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);
update
it seems if use json.stringify( arr of myimage ) not work when loaded in.
that's because json serializes data, not methods or functions. if want restore array of myimage
objects, should this:
var images = json.parse(data).map(function(image) { return new myimage(image); });
the anonymous function maps parsed data myimage
object , applied each element of resurrected array.
Comments
Post a Comment