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?
Well, for one thing,
aliasis a plain object, and therefore doesn’t have a.lengthproperty that can be used for yourforloop.If you place:
…in your
forloop, you’ll notice that you never actually run the block.And even if you fixed the loop, you’re still doing a
returnin 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 theprototypewill be included in the enumeration.