0

Consider the code below. The d1 object so created, does not have name property but why ? However, if I remove the setting of prototype as function object, things works fine. please note that below code is deliberately written like that to test how JS reacts !

function Dog(name){

  this.name = name;

}

// Notice that I am  putting function object as prototype 
Dog.prototype = function(){}

var d1 = new Dog("happy");
console.log(d1.name); //gives empty string
console.dir(d1); // `d1` does not have name property 
console.log(d1 instanceof Dog);// returns true ??
Number945
  • 4,631
  • 8
  • 45
  • 83
  • 2
    By doing this, you are destroying the constructor property – Chris Feb 05 '20 at 18:11
  • You should remove `Dog.prototype = function(){}` it resets everything. – robinvrd Feb 05 '20 at 18:12
  • 2
    "*I am putting function object as prototype*" - well, don't do that. – Bergi Feb 05 '20 at 18:12
  • @Chris , how is my Dog object getting created but without `name` property ? – Number945 Feb 05 '20 at 18:14
  • @Bergi , i was just playing with JS but now this output explanation I am not able to logically link – Number945 Feb 05 '20 at 18:15
  • @Number945 Your object is created using Object.prototype.constructor If you set your prototype to something that doesnt have a constructor...it will not work – Rainer Plumer Feb 05 '20 at 18:15
  • I don't think the duplicate target is relevant enough – Chris Feb 05 '20 at 18:18
  • Wow, I found two exact duplicates for this :-) @Chris it is. The second one I added has a better explanation though – Bergi Feb 05 '20 at 18:19
  • @Bergi, I understood that `d1` is inheriting from the new prototype and since it is anonymous function it has no `name` property and hence, the property is printed as undefined. But what happened to my `this.name =name`. After all `d1 instanceof Dog` returns true (and this another thing puzzling to me) – Number945 Feb 05 '20 at 18:34
  • @Number945 Actually the anonymous function *does* have a `.name` property, it's just the empty string (not `undefined` - what browser (version) where you using when you got that?). – Bergi Feb 05 '20 at 18:44
  • @Bergi , I ran that in chrome Version 79.0.3945.130 (Official Build) (64-bit). My bad I am getting empty string only ! Edited the code example. But why it is not taking name from constructor ? – Number945 Feb 05 '20 at 18:55
  • @Number945 See the explanation in the duplicates, and use strict mode. – Bergi Feb 05 '20 at 18:59

0 Answers0