Reputation: 12923
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?
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.
Upvotes: 3
Views: 44
Reputation: 303261
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.
Upvotes: 3