是否可以在JavaScript中创建包含某些方法的属性?

时间:2009-10-13 04:33:06

标签: javascript

请查看我所需的JavaScript。

var someVariable = new SomeDataType();

// I can directly access value of its property.
someVariable.someProperty = "test";
alert(someVariable.someProperty); // <- this command must should "test"

// However, I have some methods in above property

// I want to validate all rule in this property.
someVariable.someProperty.isValid(); // <- this method will return true/false

是否可以在当前版本的JavaScript中执行此操作?

更新

请看我的答案!

6 个答案:

答案 0 :(得分:2)

是的,您可以将Javascript函数指定为以下属性:

someVariable.someProperty = function (arg1, arg2) {
  // function code goes here
};

这是使用函数文字的方法。

另一种方法是使用这样的函数实例:

someVariable.someProperty = new Function (arg1, arg2, code);

请注意,在第二种方法中,代码作为最后一个参数进入,而Function关键字的大写“F”与方法1相比,其中“f”很小。

此外,在循环等内部创建函数实例将创建一个整个新实例来分配,这在内存中效率低下。使用函数文字方法时不会出现此问题。

答案 1 :(得分:2)

你不能(也可能不应该)在JavaScript中对待这样的对象。正如其他人提到的,你可以覆盖toString()方法来获得一半的功能(读取部分),但是你不能在没有覆盖对象的情况下对这样的对象使用赋值运算符。

您应该选择不同的方法,例如使用嵌套对象(如CMS建议的那样)。

答案 2 :(得分:2)

可能,但代码中有以下更改

function SomeDataType(){
    var localProperty="";
    this.someProperty = function(txt){
        if (arguments.length==0)
            return localProperty;
        else
            localProperty=txt;
    }       
    this.someProperty.isValid = function(){
         return (localProperty!="") ? true : false;

    };
}

不是将someProperty定义为属性,而是将其定义为函数,如果传递任何值,则将值设置为local属性,如果没有给出参数,则返回该属性值。

var someVariable = new SomeDataType();
someVariable.someProperty("test");
alert(someVariable.someProperty()); 

var isValid = someVariable.someProperty.isValid();

这是您需要访问SomeDataType对象的方式。

答案 3 :(得分:0)

someVariable.someProperty = [ test, anotherFunc, yetAnotherFunc];
someVariable.somePropertyAllValid= function() {
   for(var prop in someVariable.someProperty) {
      if(!prop()) return false;
   }
   return true;
};

someVariable.somePropertyAllValid();

答案 4 :(得分:0)

我刚刚找到答案。这很简单&amp;干净。

function createProperty(value, defaultValue, ruleCollection)
{
    this.value = value;
    this.defaultValue = defaultValue;
    this.ruleCollection = ruleCollection;       
}

createProperty.prototype.toString = function()
{
    return this.value;
};

var someVariable = 
{
    someProperty: new createProperty
    (
        'currentValue',
        'defaultValue',
        null
    )
};

对于测试,您可以使用类似我的代码。

var test = ">>" + someVariable.someProperty + "<<";

// this alert must shows ">> currentValue <<"
alert(test);


someVariable = 
{
    someProperty: new createProperty
    (
        7,
        5,
        null
    )
};

test = someVariable.someProperty + 3;

// This alert must shows "10"
alert(test);

我只是在FF 3.5&amp; IE 8.它工作正常!

<强>更新

糟糕!我忘了。因为此技术返回此属性的对象引用。因此,直接设置属性数据是不可能的。这不是我的最终答案。

答案 5 :(得分:0)

也许这会有所帮助:

var SomeVar = {
  someProperty : {
    value : 7,
    add : function (val) {
      this.value += parseInt(val, 10);
      return this;
    },
    toString : function () {
      return this.value;
    }
  }
}

alert(SomeVar.someProperty.add(3));