javascript - 在 JavaScript 的命名空间中存储可重用常量

标签 javascript design-patterns constructor

请不要将我指向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/

相关文章:

javascript - 查找数组元素索引和值的最长链

ios - Clean Swift - 没有 segue 的路由

python - 从构造函数中以正确的顺序调用加载函数

java - getConstructor() 返回一个未实现的构造函数

c++ - 改进 13 参数构造函数

javascript - 向内螺旋旋转矩阵

Javascript jquery 帮助 w/for 循环按钮

javascript - 如何在不重新启动 Express.js 项目的情况下刷新 API 端点

java - 抽象类和接口(interface)在一起?

java - 在java中设计灵活的Key类