【发布时间】:2012-12-28 04:50:35
【问题描述】:
请不要指给我Static variables in JavaScript
我的问题更具体。我是 JS 的新手(只是读了几本书,看一些截屏视频,并阅读关于 JS 中的 monoins/monads 的博客文章)所以请耐心等待))
为了存储可重用的常量,我编写了这样的代码:
函数 SVGobj(w, h) { this.value = document.createElementNS(SVGobj.svgNS, "svg"); this.value.setAttribute("版本", "1.2"); this.value.setAttribute("宽度", w); this.value.setAttribute("身高", h); } SVG obj.svgNS = "http://www.w3.org/2000/svg"; 函数 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); }上面的代码正在运行。 SVGCircle 重用常量 SVGobj.svgNS。
但我不明白 SVGobj.svgNS = 表达式。 根据 JS 规范使用 JS 表达式是否合法?
请注意,这样的代码会失败:
var SVGobj = {}; SVG obj.svgNS = "http://www.w3.org/2000/svg"; 函数 SVGobj(w, h) { this.value = document.createElementNS(SVGobj.svgNS, "svg"); this.value.setAttribute("版本", "1.2"); ... } ……有错误:
TypeError:SVGobj.prototype 未定义当我尝试实例化 new SVGobj(320, 240);
为什么?
我可以通过 new 运算符但从 "var Cls = {};" 表达式开始创建对象吗?
有人建议使用:
函数 SVGobj(w, h) { if (typeof SVGobj.svgNS == 'undefined' ) { SVG obj.svgNS = "http://www.w3.org/2000/svg"; } …… }为什么使用每次创建对象时评估的if?我的第一个例子对我来说似乎更自然......
【问题讨论】:
-
在 cmets 到 bsdev.blogspot.com/2011/02/static-variables-in-javascript.html 的人建议我的第一个解决方案...
-
var SVGobj = {};使SVGobj不是函数... -
所以任何 function SVGobj() {} 定义都被忽略了吗?或者它们一定是非法的?
标签: javascript design-patterns constructor