Please don't point me to Static variables in JavaScript
My question is more specific. I newbie to JS (just read a couple of books, see some screencasts, and read blog articles about monoins/monads in JS) so be patient ))
To storing reusable constants I write such code:
function SVGobj(w, h) { this.value = document.createElementNS(SVGobj.svgNS, "svg"); this.value.setAttribute("version", "1.2"); this.value.setAttribute("width", w); this.value.setAttribute("height", h); } SVGobj.svgNS = "http://www.w3.org/2000/svg"; function SVGCircle(cx, cy, r) { this.value = document.createElementNS(SVGobj.svgNS, "circle"); this.value.setAttribute("cx", cx); this.value.setAttribute("cy", cy); this.value.setAttribute("r", r); }
Above code is working. SVGCircle reuse constant SVGobj.svgNS.
But I don't understand SVGobj.svgNS = expression. Is that legal use of JS expressions according to JS spec?
Note that such code fail:
var SVGobj = {}; SVGobj.svgNS = "http://www.w3.org/2000/svg"; function SVGobj(w, h) { this.value = document.createElementNS(SVGobj.svgNS, "svg"); this.value.setAttribute("version", "1.2"); ... } ....
with error:
TypeError: SVGobj.prototype is undefined
when I try instantiate new SVGobj(320, 240);
Why?
Can I create object by new operator but starting from "var Cls = {};" expression?
Someone suggest to use:
function SVGobj(w, h) { if (typeof SVGobj.svgNS == 'undefined' ) { SVGobj.svgNS = "http://www.w3.org/2000/svg"; } .... }
Why use if which evaluated each time I create object?? My first example seems more natural to me...