0

understanding Map.prototype javascript

Hi all... I have gone through many example and tutorials to understand what Map.prototype actually represents.. in some blogs i saw that it represents Map object but if i have created two Map objects in the same file which one it will refer to? and can anyone please tell what the below condition mean?

var temp = Map.prototype ? new Map() : {} ;

are they checking if any objects of Map created if yes then create new object??

kumar
  • 708
  • 4
  • 15
  • 39
  • 4
    [How does JavaScript .prototype work?](http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work) – Andreas Dec 28 '16 at 16:11
  • You should research and READ a little bit : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/prototype AND https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map – Jason Krs Dec 28 '16 at 16:12
  • 1
    yes Andreas... i want to know how javascript .prototype work – kumar Dec 28 '16 at 16:15

1 Answers1

1

That condition is very strange, for more than one reason.

  1. It looks like it's trying to see if Map is supported by the JavaScript engine it's running on (Map was introduced in ES2015, not all engines have it yet), but the check is flawed and will actually throw an error if the implementation doesn't have Map. The check should be at least:

    var temp = typeof Map != "undefined" && Map.prototype ? new Map() : {} ;
    
  2. The end result is that you have temp which might be a plain object, or might be a Map instance. But you don't use Map instances and plain objects the same way, so it's strange to do that.

Frankly, I wouldn't worry about that line (and I'd be wary of it and the code around it).

I have gone through many example and tutorials to understand what Map.prototype actually represents.. I have gone through many example and tutorials to understand what Map.prototype actually represents.. in some blogs i saw that it represents Map object but if i have created two Map objects in the same file which one it will refer to?

The object that Map.prototype refers to is the object that will be used as the prototype of Map instances. That is:

let m1 = new Map();
let m2 = new Map();

Both of those instances will share the same underlying prototype object, which is the one that Map.prototype referred to.

That underlying prototype is what gives the instances various features, like the get and `set methods.

This aspect of your question is covered in more detail in How does JavaScript .prototype work?.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875