S
S
Sergey Gladyshev2018-02-14 11:17:12
JavaScript
Sergey Gladyshev, 2018-02-14 11:17:12

js. Oddities with prototype?

Good afternoon.
There is a function

Array.prototype.UContainsCustom = function(closure)
{
    var i, pLen = this.length;
    for (i = 0; i < pLen; i++)
    {
        if (closure(this[i])) { return i; }
    }
    return -1;
}

the problem is that because of this function, strange things happen in the loop:
console.log(currentOffer.IMAGES);
                for (i in currentOffer.IMAGES) {
                    img = currentOffer.IMAGES[i];
                    console.log(img);
                    
                }

first console.log shows
0: "/upload/iblock/0b2/0b223b35e0910f3adb978064abeb335c.jpg"
1: "/upload/iblock/5b7/5b7dfa007d387fab8cca969ca14cdc42.jpg"

everything is ok here.
the second console.log shows already showing weirdness:
/upload/iblock/0b2/0b223b35e0910f3adb978064abeb335c.jpg
/upload/iblock/5b7/5b7dfa007d387fab8cca969ca14cdc42.jpg
function(closure)
{
    var i, pLen = this.length;
    for (i = 0; i < pLen; i++)
    {
        if (closure(this[i])) { return i; }
    }
    return -1;
}
those. on the third iteration, which should not be, the code of this function is displayed.
How can this be explained?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stalker_RED, 2018-02-14
@Resident234

In JavaScript, object properties can be enumerable or non-enumerable...
Enumerated properties participate in iteration in a for...in loop...

https://developer.mozilla.org/en/docs/Web/JavaScript...

S
Sergey delphinpro, 2018-02-14
@delphinpro

for (i in currentOffer.IMAGES) {
  if (!currentOffer.IMAGES.hasOwnProperty(i)) continue; // magic here =))
  img = currentOffer.IMAGES[i];
  console.log(img);
}

S
Sergey Melnikov, 2018-02-14
@mlnkv

Strangeness not with ptototype, but with the study of language features Extending the
prototype of built-in classes (Array, Object, String etc.) is considered bad practice (shit code), but if you really need it, you need to set the flag enumerable = false for the new properties of the prototype object

Object.defineProperty(Array.prototype, 'UContainsCustom ', {
  value: function(closure) {
    var i, pLen = this.length;
    for (i = 0; i < pLen; i++) {
        if (closure(this[i])) return i;
    }
    return -1;
  }
});

https://developer.mozilla.org/en/docs/Web/JavaScript...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question