Javascript Koans - cannot solve one test

I am trying to solve a test from Javascript Koans and am stuck on a reflection block. Can someone solve and explain the solution for the following block:

    test("hasOwnProperty", function() {
    // hasOwnProperty returns true if the parameter is a property directly on the object, 
    // but not if it is a property accessible via the prototype chain.    
    var keys = [];
    var fruits =  ['apple', 'orange'];
    for(propertyName in fruits) {
        keys.push(propertyName);
    }
    ok(keys.equalTo(['__','__', '__']), 'what are the properties of the array?');

    var ownKeys = [];
    for(propertyName in fruits) {
        if (fruits.hasOwnProperty(propertyName)) {
            ownKeys.push(propertyName);
        }
    }
    ok(ownKeys.equalTo(['__', '__']), 'what are the own properties of the array?');
    });
0
source share
1 answer

You should be aware that JavaScript has a prototype inheritance model instead of classic. In fact, this means that inheritance is done through so-called prototype chains.

When you try to access the properties of an array using "for in", it will go up the prototype chain up to arrayname.prototype, since it inherits it!

, JavaScript Garden Ivo Wetzel, !

, javascript , .: First Property - '0', Second - '1' ..

, :

test("hasOwnProperty", function() {
// hasOwnProperty returns true if the parameter is a property directly on the object, 
// but not if it is a property accessible via the prototype chain.
var keys = [];
var fruits =  ['apple', 'orange'];
for(propertyName in fruits) {
    keys.push(propertyName);
}
ok(keys.equalTo(['0', '1', 'fruits.prototype'), 'what are the properties of the array?');

var ownKeys = [];
for(propertyName in fruits) {
    if (fruits.hasOwnProperty(propertyName)) {
        ownKeys.push(propertyName);
    }
}
ok(ownKeys.equalTo(['0', '1']), 'what are the own properties of the array?');

});

+1

All Articles