1

This is a conceptual question I wasn't skillful to solve.

The whole question can be reduced to this line:

OurConstructor.prototype = {
   a: function(){},
   b: function(){ a(); }
};

Can we call a() inside b(), both being on the prototype?


Edit: Just for other people, I was calling this.a() with the wrong name, but using b: function(){ this.a(); } should work just fine.

Codor
  • 17,447
  • 9
  • 29
  • 56
  • I dont think you should be attaching that to the prototype.. – EugenSunic Aug 22 '20 at 21:14
  • You mean because of the constructor? Well, but that's another topic. I just tried to make things brief. –  Aug 22 '20 at 21:15
  • @TiiJ7 I believe that answer is false, I've tried that already –  Aug 22 '20 at 21:20
  • 1
    ``` var OurConstructor = function(){ } OurConstructor.prototype.a = function() { console.log('func a') } OurConstructor.prototype.b = function() { this.a(); console.log('func b') } const ourConst = new OurConstructor(); ourConst.b() ``` – EugenSunic Aug 22 '20 at 21:21
  • To answer your question: In this current case. It will result in an error. Because a() is not inside the scope of b. In order to run a. You will have to call it with the "this" keyword. – Muhammad Kamran Aug 22 '20 at 21:22
  • 1
    @misternobody it s not false, check my comment above, your question is a duplicate – EugenSunic Aug 22 '20 at 21:22
  • @MuhammadKamran Yes, I should have included that, the problem is I've tried already, so I'm quite surprised. I will test again. –  Aug 22 '20 at 21:23
  • @EugenSunic mate slow down, I've tried that already, and it's simple. For some reason it didn't work, so i'm checking where is the difference. –  Aug 22 '20 at 21:24
  • I tried the following and it works: OurConstructor.prototype = { a: function( ){ console.log('asdf') }, b:function( ){ this.a()} } OurConstructor.prototype.b(); – Muhammad Kamran Aug 22 '20 at 21:24
  • @MuhammadKamran I am accessing other values from the prototype on those functions. I know it works in this example, I tried to keep it simple and that's why there is a misunderstood. –  Aug 22 '20 at 21:24
  • 1
    Not sure why anyone is voting to re-open this...it is a complete duplicate fully answered in the other question – charlietfl Aug 22 '20 at 21:43

0 Answers0