请不要将我指向Static variables in JavaScript
我的问题更具体。我是 JS 的新手(只读了几本书,看了一些截屏视频,并阅读了关于 JS 中的 monoins/monads 的博客文章)所以请耐心等待))
为了存储可重复使用的常量,我写了这样的代码:
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); }
以上代码有效。 SVGCircle 重用常量 SVGobj.svgNS。
但是我不明白SVGobj.svgNS = 表达式。 根据 JS 规范,这种 JS 表达式的使用是否合法?
注意这样的代码会失败:
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"); ... } ....
有错误:
TypeError: SVGobj.prototype is undefined
当我尝试实例化 new SVGobj(320, 240);
为什么?
我可以通过 new 运算符创建对象但从 "var Cls = {};" 表达式开始吗?
有人建议使用:
function SVGobj(w, h) { if (typeof SVGobj.svgNS == 'undefined' ) { SVGobj.svgNS = "http://www.w3.org/2000/svg"; } .... }
为什么每次创建对象时都使用 if 进行评估??我的第一个例子对我来说似乎更自然......
最佳答案
But I don't understand SVGobj.svgNS = expression. Is that legal use of JS expressions according to JS spec?
是的,SVGobj 是一个函数,svgNS 是函数的一个属性。
when I try instantiate new SVGobj(320, 240); Why?
是名称冲突。
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"); ... }
不要忘记 Javascript 不是一种面向对象的语言。
Can I create object by new operator but starting from "var Cls = {};" expression?
这个表达式等于({}只是一个捷径)
var Cls = new Object();
Why use if which evaluated each time I create object?? My first example seems more natural to me...
第一个示例比 if 解决方案更好,但代码可以更简洁。(但它总是可以。;-)
关于javascript - 在 JavaScript 的命名空间中存储可重用常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14314868/