Jump to content
  • 0

Объясните код пожалуйста


Zzz_
 Share

Question


<div id="menu">
<button data-action="save">Нажмите, чтобы Сохранить</button>
<button data-action="load">Нажмите, чтобы Загрузить</button>
</div>
<script>
function Menu(elem) {
this.save = function() { alert('сохраняю'); };
this.load = function() { alert('загружаю'); };
var self = this;
elem.onclick = function(e) {
var target = e && e.target || event.srcElement; // получает элемент по которому кликнули
var action = target.getAttribute('data-action'); // получает значение аргемента
if (action) { //
self[action](); // ВОТ ЗДЕСЬ ЧТО ДЕЛАЮТ и для чего?
} //
};
}
new Menu(document.getElementById('menu'));
</script>

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0


self[action](); // ВОТ ЗДЕСЬ ЧТО ДЕЛАЮТ и для чего?

вызывается метод полученный из аттрибута data-action

ибо вызовы:


self.save();
self["save"]();

Делают одно и тоже.

массивы в javascript это тоже объекты.

пример:


//массив
var a = [
function(){return "a1"},
function(){return "a2"}
];
//или объект
var o = {
0: function(){return "o1"},
1: function(){return "o2"},
o3: function(){return "o3"}
};
alert( a[0]() );//вернет a1
alert( a[1]() );//вернет a2
alert( o[0]() );//вернет o1
alert( o[1]() );//вернет o2
alert( o.o3() );//вернет o3

Edited by wwt
  • Like 2
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy