使用命名空间常量作为对象键? [英] Using namespace constants as object keys?

查看:107
本文介绍了使用命名空间常量作为对象键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 Javascript 对象中使用字符串常量而不是直接字符串(在定义参数键等时).目的是让 IDE 为我的代码编制索引,提供建议、自动更正/完成以及所有防错功能.

I want to use string constants instead of direct strings across my Javascript objects (when defining parameter keys, etc.). The purpose is to have my code indexed by IDE, have suggestions, auto-corrections / completitions, all the error-proof goodies.

我想为这个类的构造函数定义显式键EPPZObject,所以我做到了:

I want to define explicit keys for the constructor of this class EPPZObject, so I did:

var EPPZ =
{
    width: 'width',
    height: 'height'
}

var EPPZObject = Class.extend
({

    construct: function(parameters)
    {
        // Constant usage works fine here.
        log(parameters[EPPZ.width]);
        log(parameters[EPPZ.height]);
    }

});

在客户端代码中,我也可以使用常量:

In client code, I can use the constants as well:

log(EPPZ.width); // Logs 'width' just fine.
log(EPPZ.height); // Logs 'height' just fine.

但是当我想在构造时使用常量时(实际上这就是重点),那么它就行不通了:

But when I want to use the constats while constructing (that would be the whole point actually), then it just not works:

var objectThatWorks = new EPPZObject(
        {
            'width' : '9',
            'height' : '9',
        });

var objectThatNotWorks = new EPPZObject(
        {
            EPPZ.width : '9',
            EPPZ.height : '9',
        });

它说:

Uncaught SyntaxError: Unexpected token . 

如何解决这个问题?是否有类似的干净解决方案来使用常量?

How to get over this? Is there a similarly clean solution to use constants?

推荐答案

你能不能做一个这样的单身人士?:

Cant you make a Singleton like this?:

var EPPZ = {
        width : '9',
        height : '9'
};

然后也许

var objectThatWorks = new Object();
objectThatWorks.width = EPPZ.width;
objectThatWorks.height = EPPZ.height;

编辑

你尝试过原型设计吗?

EPPZObject.prototype.width = EPPZ.width;

这篇关于使用命名空间常量作为对象键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆