// Создайте объект calculator с методами: // read() запрашивает prompt для двух значений и сохраняет их как свойства объекта x, y // sum() возвращает сумму этих двух значений // multi() возвращает произведение этих двух значений // diff() возвращает разницу // div() возвращает частное var calculator = {}; calculator.read = function () { this.x = +prompt('значение х'); this.y = +prompt('значение y'); } calculator.sum = function () { return this.x + this.y; }; calculator.multi = function () { return this.x * this.y; } calculator.diff = function (){ if (this.x < this.y){ return this.y - this.x; } else { return this.x - this.y; } } calculator.div = function (){ if (this.x < this.y){ return this.y / this.x } else { return this.x / this.y } } calculator.read(); alert( calculator.sum() ); alert( calculator.multi() ); // 2. Создайте объект coffeeMachine со свойством message: ‘Your coffee is ready!’ и методом start(), при вызове которого – coffeeMachine.start() – // через 3 секунды появляется окно с сообщением, записанным в свойстве объекта message. var coffeeMachine = { message : 'Your coffee is ready!', start : setTimeout(function() { alert(coffeeMachine.message); }, 3000), } // 3. Создайте функцию hello(), которая выводит приветствие пользователю. Создайте два объекта, содержащие поля firstname, lastname. Используя метод call и функцию // hello() приветствуйте каждого из пользователей персонально. var hello = function() { alert("hello " + this.firstname + ' ' +this.lastname); } var firstUser = { firstname : 'Jone', lastname : 'Dou', }; var secondUser = { firstname : 'Baby', lastname : 'Dou', }; hello.call(firstUser); hello.call(secondUser); // 4. Создайте объект counter с методами увеличения, уменьшения значения счетчика и методом возврата текущего значения. // Используйте концепцию chaining для создания цепочки вызовов. var counter = { count : 0, }; counter.inc = function() { this.count++; return this; }; counter.dec = function() { this.count--; return this; }; var current = counter.inc().inc().dec().inc().dec(); alert(current); // 5. Создайте объект с данными: x, y и методами: getSum, getDiff, getMulti, getDiv. Методы объекта ничего не реализуют, а только выводят в alert сообщения вида ‘1 + 1 = 2’ // или ‘1 / 0 = Infinity’. Для расчетов все методы используют функционал ранее созданного калькулятора. var me = {}; me.getSum = function(x , y) { this.x = x; this.y = y; return +this.x + '+' + +this.y + '=' + +calculator.sum.call(this); }; me.getDiff = function(x , y) { this.x = x; this.y = y; if (this.x < this.y){ return +this.y + '-' + +this.x + '=' + +calculator.diff.call(this); } else { return +this.x + '-' + +this.y + '=' + +calculator.diff.call(this); } }; me.getMulti = function(x , y) { this.x = x; this.y = y; return +this.x + '*' + +this.y + '=' + +calculator.multi.call(this); }; me.getDiv = function(x , y) { this.x = x; this.y = y; if (this.x < this.y){ return +this.y + '/' + +this.x + '=' + +calculator.div.call(this); } else { return +this.x + '/' + +this.y + '=' + +calculator.div.call(this); } }; alert(me.getSum(1, 1)); alert(me.getDiv(1, 0)); // 7. Создайте объект со свойством delay и методами appendTo и appendText. Метод appendTo с помощью jQuery добавляет абзац в контейнер, переданный в параметре метода. // Метод appendText может дописывает текст в добавленный элемент. Создайте массив строк и запустите цикл по этому массиву. С периодичностью, определенной в свойстве delay, // в текст добавленного html-элемента добавляется соответствующий по порядку элемент массива. Учтите, что для доступа к вашему элементу не должен производиться поиск // по DOM-дереву. var arr = ['dsfsd','asfasf','afsf','saf','fasffs','fasf'] var obj = { delay : 3000, appendTo : function (target) { $(target).append('
'); }, appendText : function (text) { $('p').append(text); } }; obj.appendTo('body'); for (var i = 0; i < arr.length; i++) { (function(i) { setTimeout( function () { obj.appendText(arr[i] + ' '); }, obj.delay+ i * 1000) })(i) }; // 8. Есть следующий код:var country = { // name: 'Ukraine', // language: 'ukrainian', // capital: { // name: 'Kyiv', // population: 2907817, // area: 847.66 // } // }; // function format(start, end) { // console.log(start + this.name + end); // } // Допишите код, чтобы в консоли браузера появились строки, которые написаны в комментариях: // format.call(/* Ваш код */); // Ukraine // format.apply(/* Ваш код */); // [Ukraine] // format.call( Ваш код ); // Kyiv // format.apply(/* Ваш код */); // Kyiv // format.apply(/* Ваш код */); // undefined var country = { name: 'Ukraine', language: 'ukrainian', capital: { name: 'Kyiv', population: 2907817, area: 847.66 } }; function format(start, end) { console.log(start + this.name + end); }; format.call(country, '', ''); format.apply(country, ['[' ,']']); format.call(country.capital, '', ''); format.apply(country.capital, ['', '']); format.apply(window ,['']); //9. Создайте объект user с полем name. Создайте функцию format с параметрами start и end: // Привяжите функцию format() к объекту user таким образом, чтобы ее вызов возвращал отформатированное имя пользователя // Реализуйте 2 версии текущего задания, используя: // 2. Метод bind(). var user = { name : 'Jone' }; function format(start, end) { console.log(start + this.name + end); }; var userFormat = format.bind(user, '<<<', '>>>'); userFormat(format.bind(user)); // 1. Анонимную функцию; var user = { name : 'Jone' }; function format(start, end) { console.log(start + this.name + end); }; userFormat userFormat('<<<', '>>>'); // 10. Напишите функцию concat, которая соединяет две строки, разделенные каким-то символом: разделитель и строки передаются в параметрах функции. Используя карринг, // создайте новую функцию hello, которая которая выводит приветствие тому, кто передан в ее параметре: function concat(str1, sep, str2) { return console.log(str1+sep+str2); } var hello = concat.bind(null, "Hello", " "); hello('World'); hello('John');