对象是否只能包含访问器属性(对象不应该包含任何数据属性)?

时间:2017-12-24 07:18:11

标签: javascript ecmascript-6

var student={};
 Object.defineProperty(student,"name",{
                        get:function(){
                            this.name;
                          },
                       set:function(){
                            this.name=name;
                          }
                  });

我假设如果我分配student.name =“xyz”,名称属性将添加到student对象。我在混淆时何时以及如何使用访问者属性。

3 个答案:

答案 0 :(得分:0)

Object.defineProperty用于处理configurableenumerablewritablegetset等属性。使用get和在你的代码中设置,我没有看到做任何事情的任何意义。你可能想要在前任时使用它们。通过写入或取回数据来改变数据。

更改这些属性的更明显的好处,你可以看到ex。 writable

var obj = { name: 'foo' }

obj.name // 'foo'
obj.name = 'bar' 
obj.name // 'bar'

Object.defineProperty(obj, 'name', {writable: false}
obj.name = 'foo'
obj.name // 'bar'

enumerable

var o = {name: 'foo', lastName: 'bar'}
Object.defineProperty(o, 'name', {enumerable: false})
for(var prop in o) { console.log(prop)} // lastName

答案 1 :(得分:0)

一个好的用例是在设置一个属性时修改对象,例如:

 const person = {
   firstName: "Jonas",
   lastName: "W.",

   get fullName(){ return this.firstName + " " + this.lastName;},
   set fullName(name){
     const [first, last] = name.split(" ");
     this.firstName = first;
     this.lastName = last;
   }
 };

所以可以这样做:

 person.fullName = "Max Mustermann";
 console.log(person.firstName, person.lastName);  

答案 2 :(得分:0)

属性访问器的用例是当您需要对正在设置的属性执行某些数据验证时。

public class CustomAdapter extends ArrayAdapter<Item> implements View.OnClickListener{

private ArrayList<Item> dataSet;
Context mContext;

private static class ViewHolder {
    TextView txtName;
    ImageView btn;

}



public CustomAdapter(ArrayList<Item> data, Context context) {
    super(context, R.layout.list_item, data);
    this.dataSet = data;
    this.mContext=context;

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Item dataModel = getItem(position);

    final ViewHolder viewHolder; 

    if (convertView == null) {
        viewHolder = new ViewHolder();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.list_item, parent, false);
        viewHolder.txtName = (TextView) convertView.findViewById(R.id.text);
         viewHolder.btn= (ImageView) convertView.findViewById(R.id.expand_button);
         viewHolder.txtName.setText(dataModel.getText());


        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    viewHolder.position= position;


    return convertView;
}

@Override
public int getViewTypeCount() {
    return 1;
}

@Override
public int getItemViewType(int position) {
    return super.getItemViewType(position);
}

@Override
public int getPosition(@Nullable Item item) {
    return super.getPosition(item);
}

@Override
public long getItemId(int position) {
    return super.getItemId(position);
}  }