简体   繁体   中英

Javascript Koans - cannot solve one test

I'm trying to solve test from Javascript Koans and stuck on "reflection" block. Could anyone solve and explain solution for next 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?');
    });

You must know that JavaScript features a prototypal inheritance model instead of a classical one. In fact, what this means is that inheritance is done through what is called prototype chains .

When you try to access an array's properties with a "for in", it will "climb up" the prototype chain all the way to arrayname.prototype, since it inherits from it !

If you want to learn more about this feature, I strongly suggest you take a look at JavaScript Garden from Ivo Wetzel, which is where I initially found my answers !

For the rest, you should also know that javascript refers to an array's "own" properties as decimal numbers, ie.: First Property is '0', Second is '1', etc.

So, solution goes like this :

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?');

});

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