简体   繁体   中英

Why can't I call a setter via the string defined in an object?

Let's consider the following:

export default () => {
  let _message = '';

  return  {

    set message(msg) {
       _message = msg;
    },

    get message() {
      return _message;
    }
  }
}

Let's assume you import this as Message .

const message = Message();

Now let's give you an object: const messageObject = {setterName: 'message'};

So let's do this:

const setterName = messageObject.setterName;
message.setterName = 'hello world';

console.log(message.message); // => ''

Why is this empty? Why can I not do this? Is there something I missing?

How would I make this work, if possible?

Update

Some of you seem to be deeply confused. Lets consider how you would actually use the above code as opposed to how I am using it:

const message = Message();
message.message = 'hello world';
console.log(message.message); // => 'hello world';

The object:

const messageObject = {setterName: 'message'};

contains a setterName key, with a vale of 'message' . In this case I should be able to do the exact same thing as I did above, accept I should be able to use setterName :

const setterName = messageObject.setterName; // This is message. Remember that.
message.setterName = 'hello world';

// The above (should) in my mind should be the same as:
// message.message = 'hello world';

console.log(message.message); // (should) => 'hello world'

I hope this makes things more clear. In other languages like PHP I would do:

call_user_func_array(array(Message, 'setMessage'), array('hello world'));

Notice how setMessage is in quotes. Well I am trying to do the same thing here.

Consider this:

var o1 = { prop:"cats" };
var o2 = { cats:42 };
var propertyName = o1.prop;
console.log( o2.propertyName  ); // undefined
console.log( o2[propertyName] ); // 42

You set setterName to the string "message" (via a convoluted route, as I did above), but then you try to talk to message.setterName —the property NAMED "setterName"—instead of message[setterName] which is the same as message.message .

If you change your code to:

message[setterName] = 'hello world';

…then it will do what (I think) you are trying to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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