javascript - What does it mean to add a prototype to a function? -


this question has answer here:

given:

var x = function () {  };   x.prototype = { abc: 25 }; 

can explain me means. done inside function without .prototype?

var x = function () {   // here ? }; 

prototypes how class model works in javascript - you've created class x has property abc defaults 25:

var obj = new x(); alert(obj.abc);   // 25 

the function x class constructor, called when new instance of class created , can initialize it. , means of course can set abc property there:

var x = function() {   this.abc = 25; }; var obj = new x(); alert(obj.abc);   // 25 

this supposedly less efficient approach however:

  • you have manipulate each object created rather setting property on prototype once , forever.
  • the property stored on each object , consumes memory each time, opposed being stored once on prototype.

ecmascript harmony has nicer syntax defining classes , prototypes, 1 isn't implemented in browser yet:

class x {   constructor() {     ...   }    public abc = 25; } 

this equivalent code defining prototype, merely grouping related operations little better.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -