1

I wonder if there is a way to have a default return value for a javascript object. I'll try to explain with an example:

I have:

Obj1 = {'prop1' = 'something1',
        'prop2' = 'something2',
        'active' = typeof XMLobj.propX === 'undefined' ? false : true} //XMLobj comes from somewhere else

since I want this object to be part of another object, I would like to have something like

If (otherObj.Obj1) { //do something using prop1 and/or prop2 }.

where otherObj.Obj1 to return the value of the active field, instead of having to check for otherObj.Obj1.active

The reason behind is likely bad code (my fault). I wrote several functions using something using If (otherObj.Obj1). I didn't care care about it's properties at the time, but now I'd like to further expand, and I would like to avoid (if possible using somethig like this:

otherObj.Obj1 = typeof XMLobj.propX === 'undefined' ? false : true} //XMLobj comes from somewhere else
otherObj.Obj1Prop1 = 'something1'
otherObj.Obj1Prop2 = 'something2'

any advice? thanks

4

2 回答 2

0

仅引用对象时,JavaScript 不会从对象返回字段。它必须返回对象本身。在某些具有静态类型信息的语言中,这可能会发生(我认为 VB 是这样做的)。JavaScript 没有静态类型,所以它需要返回对象。它无法告诉何时返回对象以及何时返回对象中的“默认”字段。

于 2013-06-07T18:18:59.333 回答
0

这是不正确的对象文字表示法:

Obj1 = {'prop1' = 'something1',
        'prop2' = 'something2',
        'active' = true or false}

应该:

var someCondition = // Make this evaluate to true or false based on whether it's active.
var otherObj = {Obj1 : {prop1: 'something1',
        prop2: 'something2',
        active: someCondition ? true : false}
        };

active检查对象属性的常规方法:

if(otherObj.Obj1.active) { //do something using prop1 and/or prop2 }.

如果你这样做:otherObj.Obj1 = true;你正在消灭你的对象

于 2013-06-07T18:23:24.807 回答