简体   繁体   English

如何返回JS文字对象的默认属性?

[英]How to return a default property of JS literal object?

One JS object is defined like this: 一个JS对象定义如下:

var obj = {
      key1 : {on:'value1', off:'value2'},
      key2 : {on:'value3', off:'value4'}
}

Is there a tricky way, to pick a default key1 on property, when the obj.key1 is passed without property? 当没有属性传递obj.key1时,是否有一种棘手的方法, on属性on选择默认key1

var key1State = obj.key1; // I want to receive 'value1' here, not obj.key1{...}

Is it somehow generally possible to recognize in the object definition body which property (if at all) is passed/asked during the object call? 是否通常可以在对象定义体中识别在对象调用期间传递/询问哪个属性(如果有的话)?

I'm not sure if this is what you need, but messing with valueOf or toString may be what you're looking for. 我不确定这是否是你需要的,但是使用valueOftoString可能正是你正在寻找的东西。

For example: 例如:

var obj = {
      key1 : {on:'value1', off:'value2', toString : function(){ return this.on; }},
      key2 : {on:'value3', off:'value4', toString : function(){ return this.on; }}
}

var key1State = obj.key1; // the object
var key1StateStr = '' + obj.key1; // string "value1"
obj.key1 == "value1"  // true
obj.key1.toString() === "value1"  // true

So if you were going to use the default value as a string somewhere this may be useful. 因此,如果你打算在某个地方使用默认值作为字符串,这可能会有用。

This does not fix your case, but you may find it useful. 这不能解决您的问题,但您可能会发现它很有用。

Use getters. 使用getters。

var obj = {

  key1 : {on:'value1', off:'value2'},
  key2 : {on:'value3', off:'value4'}, 
  get fooBar () { return this.key1.on }

}

now obj.fooBar returns keyq.on 现在obj.fooBar返回keyq.on

I am understand your idea, but think the better way here is to use function like getState for getting actual state of object. 我理解你的想法,但认为更好的方法是使用像getState这样的函数来获取对象的实际状态。

var obj = {
  key1: {on:'value1', off:'value2'},
  key2: {on:'value3', off:'value4'}
};

var key1State = getState(obj.key1);
var key2State = getState(obj.key2.off);

function getState(obj) {
  return obj.on || obj;
}

console.log(key1State, key2State);

See codepen. 见codepen。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM