0

I am trying to understand why the result when I call the below function is "no" because the property c should exist. Does anyone know why? Thanks!!!

var letters = function() {
    this.a = 5;
    this.b = 20;
  };

  letters.prototype = {
    c: 10
  };

  var letters = new letters();

function looping(obj){
if (obj.hasOwnProperty(this.c)) {
console.log("ua");
}
else {
    console.log("no");
}
}

looping(letters);

learningcoding
  • 187
  • 2
  • 14

2 Answers2

2

It doesn't "have own property" c though. c is part of its prototype, so it's not an own property of the object you are testing.

At least, that's what the answer would be if you were calling obj.hasOwnProperty('c') as you probably intended. What you're actually calling is obj.hasOwnProperty(window.c), which is obj.hasOwnProperty(undefined), which is clearly false.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

The argument to hasOwnProperty should be a string.

console.log(obj.hasOwnProperty("c") ? "UA" : "no")

Also the whole point of hasOwnProperty is to tes that the property /isn't/ obtained from the prototype, so the test should fail.

George Simms
  • 3,930
  • 4
  • 21
  • 35
  • What I wanted to do is this: function looping(obj){ var properties=[]; if (!obj.hasOwnProperty("c")) { properties.push(key); } return properties; } //so only push it to the properties array if its not the c property-thus pushing ll properties BUT that particular property, thats what I tried testing with hasOwnProperty – learningcoding May 13 '16 at 18:06
  • sorry I missed to include the loop // for (var key in obj) – learningcoding May 13 '16 at 19:09
  • Right, I guess you want something like `function (o) { return Object.keys(o).filter(function (k) { return !o.hasOwnProperty(k) }) }`. But some more context would be helpful. – George Simms May 14 '16 at 16:39