David G
David G

Reputation: 96845

Why does the hasOwnProperty alias falsely return undefined?

function object() {
    var F = function() {};
    F.prototype = {
        alias: {},
        hasOwnProperty: function() { return false; },
        hasProperty: function(obj, prop) {
            for (var i = 0; i < obj.length; i++) {
                if (obj[i] !== prop) return false;
                else if (obj[i] === prop) return true;
                else return undefined;
            }
        }
    };
    return new F();
}

var newObj = object();
newObj.alias.msg = "Hello";
console.log(newObj.hasProperty(newObj.alias, "Hello"));

It returns undefined for newObj.hasProperty(newObj.alias, "Hello"). Why?

Upvotes: 0

Views: 348

Answers (2)

user113716
user113716

Reputation: 322562

Well, for one thing, alias is a plain object, and therefore doesn't have a .length property that can be used for your for loop.

If you place:

console.log(i);

...in your for loop, you'll notice that you never actually run the block.

And even if you fixed the loop, you're still doing a return in the very first enumeration, so if the property you're testing isn't first in the loop, you'll get an incorrect result.

Ultimately, you won't be able to replicate the behavior of hasOwnProperty() with a loop, because the prototype will be included in the enumeration.

Upvotes: 0

Jani Hartikainen
Jani Hartikainen

Reputation: 43253

It's most likely because you're iterating an object as if you were iterating an array.

The for-loop never loops anything at all, because objects don't have a length property, and aren't indexed by number.

You need to use a for-in loop:

for(var key in obj) {
    //key will contain the name of the property, and obj[key] the value
    if(key === blah) ...
}

Upvotes: 1

Related Questions