0

I am trying to differentiate between first block and second block of code.

//first block
 function xyz(){
   this.callXyz=function(){
     console.log('callXyz inner');
   }
}
// second block
xyz.prototype.callXyz=function(){
     console.log('prototype function');   
}
Vishal Pachpande
  • 500
  • 5
  • 19

1 Answers1

0

I'm going to guess that your first code block was meant to look like this:

function xyz(){
   this.callXyz = function(){
     console.log('callXyz inner');
   }
}

And I'm going to assume you do new xyz at some point to create an instance.

If so, the difference is that in that first example, a new function is created each time xyz is called (presumably via new) and assigned as an own property on the new object. In the second example, the function is only created once, and then the new object created by new xyz gets that property as an inherited property from its prototype; all of the instances created via new xyz share the same function.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • The first part of this answer is misleading as you are making assumptions about the SO's code. The Question is clear but the code he has given is misleading, and as such, anyone who references this later will be lost. – Nelson Owalo Oct 03 '18 at 12:56
  • @PlatinumIndustries - No, this isn't misleading, because I noted the error **right at the outset** of the answer (and [in a comment](https://stackoverflow.com/questions/52627383/can-anyone-tell-me-the-difference-between-function-defined-in-function-and-addin/52627451?noredirect=1#comment92188194_52627383)). This is the most likely thing the OP meant. – T.J. Crowder Oct 03 '18 at 13:06
  • 1
    @PlatinumIndustries: This answer starts with "I'm going to guess that..." I made the same assumption, and the OP can explain why this assumption is wrong (and perhaps then T.J. would delete the answer) or modify the question. I see no room for future confusion caused by this answer. – Scott Sauyet Oct 03 '18 at 13:07
  • @T.J.Crowder Sorry. it seem'd to me like the 1st block was supposed to be a function wrapped in a class. Or a function wrapped in another function. It could be either. That makes the answers to be based on assumptions, which doesn't help future SO's who reference it. But I guess I worded my first comment wrongly tho. – Nelson Owalo Oct 03 '18 at 13:23