//I am trying to write the source code of hasOwnProperty
et k={h:1,b:2}
Object.prototype.hasOwnPropertys=function(property){
let value=-1
for( let i in this){
if(property===i){
return true
}
}
return false
}
let b=k.hasOwnPropertys("h")
console.log(b)
// result true
b=k.hasOwnPropertys("h8")
console.log(b)
when you have a question not related to the current topic please create a new thread
this time I will create the thread for you, next time please do it yourself.
@Eldhose Your function would incorrectly include properties defined in the prototype chain. The built-in hasOwnProperty method only looks in the object and not the prototype chain. That is why you can not use the for in loop. This was discussed in the following challenges:
See the following example of how your method does not work.
Object.prototype.hasOwnPropertys = function(property) {
let value = -1
for (let i in this) {
if (property === i) {
return true
}
}
return false
}
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.numLegs = 2;
const john = new Person('John', 36);
const x = john.hasOwnPropertys('age');
console.log(x); // shows true which is correct
const y = john.hasOwnPropertys('eyeColor');
console.log(y); // shows false which is correct
const z = john.hasOwnPropertys('numLegs');
console.log(z); // shows true which is not correct because numLegs is defined in Person's prototype.