1

I have two objects

function Obj1(name){
   this.prototype={};
   this.prototype.Name=name;
   this.prototype.getName=function(){
        alert(this.Name); 
   };
}
function Obj2(name){
   var x=new Obj1(name);
   x.prototype=Object.defineProperties(x,{
   myFunc:{
       value:function(){
       alert("I am myFunc");
       }
   }
   });
   return x;
}
var y=new Obj1("Your Name");
var z=new Obj2("Her Name");
y.getName();
z.getName();//works fine in this case

when I call z.getName() while creating the Obj2 with the following constructor function it results in an error saying "z has no method getName()"

function Obj2(name){
   //var x=new Obj(name);
   this.prototype=new Obj(name);
   this.prototype=Object.defineProperties(this.prototype,{
   myFunc:{
       value:function(){
       alert("I am myFunc");
       }
   }
   });
   //return x;
}

I get the same error when I try to do it this way

    function Obj2(name){
   var x=new Obj(name);
   x.prototype={};
   x.prototype=Object.defineProperties(x.prototype,{
   myFunc:{
       value:function(){
       alert("I am myFunc");
       }
   }
   });
   return x;
}

what's going on I am in complete confusion why don't the second and third ways of writing constructor for creating Obj2 inherit the method getName(),Is the first way of constructor inheriting or creating another copy of x with newly defined properties on x.prototype?

  • I don't believe this is the code you have. I already get `this.prototype` is `undefined` for the first example (in `Obj1`). (aside from the syntax error in `Obj2`). – Felix Kling May 06 '13 at 07:04
  • 3
    It looks like you're mixing a bunch of concepts wrongly here... – elclanrs May 06 '13 at 07:06
  • 1
    here is an example on how to use prototype on function based constructed objects http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 And how JavaScript "inherrits from parents" prototype chain works – HMR May 06 '13 at 07:09
  • @FelixKling fixed the syntax error,thanks for pointing out – Romantic Electron May 06 '13 at 07:09
  • Nope, the syntax error is still there ;) (it's in `value=function(){`) and you still have the runtime error. So, as I said, the first example *does not work fine* and hence it does not make sense to compare to it. FWIW, there are so many questions on SO regarding inheritance, you should read some of those. Your code looks a bit like you just mixed different concepts together. – Felix Kling May 06 '13 at 07:11
  • @FelixKling fixed that as well – Romantic Electron May 06 '13 at 07:15
  • 1
    prototype cannot be used on instances, use __proto__ (two underscores before and after proto) instead if you must but better is it to to define "static" properties outside the function body using Obj1.prototype. Please read the link I've posted before. – HMR May 06 '13 at 07:20

0 Answers0