M
M
Majak2011-06-27 17:02:03
JavaScript
Majak, 2011-06-27 17:02:03

How to add a property of an object in JS through a method of the same object?

It probably shouldn't be difficult, but I've been sitting for an hour and can't catch up. Help catch up.
var attr = {
    add: function(name, val) {
        this.name = val;
    }
};
attr.add('title', 'Title');
attr.add('href', '#');
As a result, I get a logical conclusion:
attr.name = '#'
But how to make the logic I'm chasing work :)
attr.title = 'Title'
attr.href = '#'
I didn't even know how to correctly and intelligibly compose a question.
Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Majak, 2011-06-27
@Majak

I don't know how bad this method is, but it seems to work :)
var attr = {
add: function(name, val) {
this[name] = val;
}
};
Well, he asked and answered himself.
But it would be interesting to hear the correct answer :) Thank you.

S
s0rr0w, 2011-06-27
@s0rr0w

And why such difficulties with the method, if you can just use
attr.title = 'Title';
attr.href = '#';
And the result will be the same...

M
Majak, 2011-06-29
@Majak

“if the stars are lit, it means that someone needs it”
For example, a tag can have different attributes, which ones (class id style selected or some special ones) are not known in advance.
And so you can automatically create an object, only with those attributes that that tag has,
in one case we will get a.attr.href and a.attr.title, and in another img.attr.alt and img.attr.src

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question