当对象定义中的/那些函数未定义时,代码如何调用对象的函数?

Kiv*_*ius 1 html javascript prototype object

我有一个图像代码

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

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

我还应该提一下,我需要做这些功能的原因是因为这个代码示例问题:(不好)

arr.getById(index).x = 100;
arr.getById(index).y = 200;
Run Code Online (Sandbox Code Playgroud)

.getById() 是数组的直接原型,循环true arr并查找指定的id.

Ja͢*_*͢ck 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.
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样创建一个新图像:

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);
Run Code Online (Sandbox Code Playgroud)

更新

似乎如果我使用JSON.stringify(MyImage的arr),它将在加载时无法工作.

那是因为JSON序列化数据,而不是方法或函数.如果要还原MyImage对象数组,则应执行以下操作:

var images = JSON.parse(data).map(function(image) {
    return new MyImage(image);
});
Run Code Online (Sandbox Code Playgroud)

匿名函数将解析后的数据映射到MyImage对象中,并将其应用于复活数组的每个元素.

  • @Jessica我不确定你的意思.你能详细说明你如何存储物品吗? (2认同)