Вывод.Объектно-ориентированное приложение JS Gallery подвергается рефакторингу двумя различными способами (объектная функция, объектный литерал):
Основной вывод: при создании функции-конструктора не забудьте использовать заглавную букву для первой буквы имени объекта (например, Gallery) и Ключевое слово 'new' (var Gallery = new Object();).
- Использование функции объекта
// Creating a custom object using the Object function name with new operator // var Gallery references newly created obj. var Gallery = new Object(); window.onload = function () { // 3 properties of Gallery obj: CurrentIndex, Images, and _loopInterval // Images prop: array that stores the images that are displayed in the gallery Gallery.Images = ['babyMeekats.jpeg', 'minx.jpeg', 'owl.jpeg']; // CurrentIndex prop: represents current ith Image of array Gallery.CurrentIndex = 0; // _loopInterval prop: auto loops thru img in the gallery every 2.5 seconds Gallery._loopInterval = setInterval(Gallery.Next, 2500); }; // 3 methods of Gallery obj are Gallery.Next, Gallery.Prev, Gallery.Display // Next method inc the current i in Images array Gallery.Next = function() { // if CurrentIndex property number inc/dec (changes to different array item) if(Gallery.CurrentIndex < (Gallery.Images.length-1)) { // go to the next ith position of img Gallery.CurrentIndex++; // if you are at the last img } else { // resets the CurrentIndex back first img Gallery.CurrentIndex = 0; } // show img Gallery.Display(); }; // Prev method dec the current i in Images array Gallery.Prev = function () { // if img is on anything other than starting ith if(Gallery.CurrentIndex > 0) { // move to one less index position Gallery.CurrentIndex--; // if you are on first img then go to last img } else { Gallery.CurrentIndex = (Gallery.Images.length - 1); } Gallery.Display(); }; // renders current img to html Gallery.Display = function() { // access to html id element var photoGallery = document.getElementById('photo-gallery'); // when app loads CurrentIndex is 0 then changes with .Next() method runs var currentImage = Gallery.Images[Gallery.CurrentIndex]; // note: Gallery.Images = ['babyMeekats.jpg', 'minx.jpg', 'owl.jpg']; // ex) Gallery.Image[0] = 'babyMeekats.jpg' photoGallery.src = "img/" + currentImage; };
2. Литеральное обозначение объекта
// Creating a custom object using literal notation var Gallery = { // adding prop Images, CurrentIndexto custom obj using literal notation // key : value (structure for def. prop) Images: ['babyMeekats.jpeg', 'minx.jpeg', 'owl.jpeg'], CurrentIndex: 0, // Adding methods to Gallery object using literal notation Next: function () { // when i is less than last element in array if(Gallery.CurrentIndex < (Gallery.Images.length - 1)) { // add one to CurrentIndex prop Gallery.CurrentIndex++; } else { // reset to first element of Images array Gallery.CurrentIndex = 0; } Gallery.Display(); }, Prev: function() { // if CurrentIndex is not at beginning if(Gallery.CurrentIndex > 0){ Gallery.CurrentIndex--; // if at beginning } else { // go to last image Gallery.CurrentIndex = (Gallery.Images.length - 1); } Gallery.Display(); }, Display: function () { var photoGallery = document.getElementById('photo-gallery'); // Images is where array of pictures live var currentImage = Gallery.Images[Gallery.CurrentIndex]; // set source (document.getElementById('photo-gallery').src) to currentImage photoGallery.src = "img/" + currentImage; } }; // when window loads toggle every 2.5 sec window.onload = function () { // setInterval is window obj native method var _loopInterval = setInterval(Gallery.Next, 2500); };
Единственный недостаток объектов, использующих функцию
Object
или литеральную нотацию, заключается в том, что вы не можете создавать их экземпляры несколько раз. Например, вы можете использовать операторnew
только с этими двумя типами объектов в начальный момент создания объекта, что означает, что вы не можете повторно использовать объект для создания другого экземпляра. Например, в этой статье, если вы хотите создать несколько галерей в одном файле HTML, вам нужно включить файл JavaScript несколько раз и каждый раз давать галерее другое имя, что приводит к большому количеству повторяющихся объектов с разными именами. . Следовательно, эти типы объектов не подходят для таких ситуаций. С другой стороны, если вам нужно использовать объект только один раз, эти типы объектов прекрасно работают. Чтобы создать объект, экземпляр которого можно создавать несколько раз, необходимо использовать конструктор объектов и прототипирование. **
*credit: https://www.ibm.com/developerworks/library/wa-oojavascript/