使用原型函数将新建的整个对象推送到数组中

Pushing newly created whole object to array with prototype function

本文关键字:对象 数组 原型 函数 新建      更新时间:2023-09-26

我正试图在我的对象的构造上运行一个函数,该函数将整个对象传递给函数,然后函数将其推送到数组。

我可以像这样一次传递一个属性:

    function Item(title, description, price) {
    'use strict';
    this.title = title;
    this.description = description;
    this.getPrice = function (price) {
        var pricestring = "£";
        pricestring = pricestring + price;
        return pricestring;
    };
    this.addToPage(this.title, this.description);
}

但我希望能够像这样通过整个对象:

this.addToPage(this.Item);

但是它总是返回undefined。

我的addToPage是这样的函数:

Item.prototype.addToPage = function (item) {
    'use strict';
    constructedItems.push(item);
};

实际上有可能从物体内部传递整个物体吗?或者还有其他我可以使用的技术吗?

您正在寻找this,它指的是正在构建的对象。