简体   繁体   中英

How to iterate through instances of a prototype “class” JS

I want a "for" or "while" loop to iterate through all the instances/objects in the prototyp/"class". like "hasNext()" in array.

Then I wanna implement a function. for instance alertname("obj") this will then return the name of obj. the problem is that I dont know the specific obj. the function only gets a string and then it'll search in the prototypes which one is the right one.

   function Product(id, name) {
    this.id = id;
    this.name = name;
}

Product.prototype.getid = function() {
    i = this.id;
    return i;
};
Product.prototype.getname = function() {
    i = this.name;
    return i;
};

balloon = new Product(0, "Balloon");
var text = "balloon";

//doesnt work
function getname(obj) {
    i = Product.prototype.getname(obj);
    window.alert(i);
}
getname(text);

It looks like you want to keep track of all the objects you create with new Product . This is something you need to implement yourself.

Just create an array:

const stock = [];
stock.push(new Product(0, "Balloon"));
// ...
stock.push(new Product(0, "Monopoly"));

Then you can simply iterate them:

for (const product of stock) {
    console.log(product.getname());
}

It is for a good reason that JS does not provide you with such an array out-of-the-box: if that were done, then none of the created objects could ever be garbage-collected; they will always be regarded as something you still need to use. So it is a good thing that there is no built-in mechanism for this.

Concerning your own attempt

Product.prototype.getname(obj);

This does not make sense: getname does not take an argument. You usually call prototype functions like methods:

obj.getname()

In some cases you would want to use Product.prototype.getname , but that is only needed when obj is not an instance of Product , but is so similar that it would work to call getname on it. In that case use .call() :

Product.prototype.getname.call(obj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM