2.4 KiB
2.4 KiB
id, title, challengeType, forumTopicId, localeTitle
id | title | challengeType | forumTopicId | localeTitle |
---|---|---|---|---|
587d7dad367417b2b2512b75 | Create a Method on an Object | 1 | 301318 | Создание метода для объекта |
Description
Objects
могут иметь особый тип property
, называемый method
. Methods
- это properties
которые являются функциями. Это добавляет другое поведение к object
. Вот пример duck
с помощью метода: let duck = {В примере добавлен
имя: «Афлак»,
numLegs: 2,
sayName: function () {return "Название этой утки -" + duck.name + ".";}
};
duck.sayName ();
// Возвращает «Название этой утки - Афлак».
method
sayName
, который является функцией, которая возвращает предложение, дающее имя duck
. Обратите внимание, что method
получил доступ к свойству name
в операторе return с помощью duck.name
. Следующая задача будет охватывать другой способ сделать это.
Instructions
object
dog
, дайте ему метод, называемый sayLegs
. Метод должен вернуть предложение «У этой собаки 4 ноги».
Tests
tests:
- text: <code>dog.sayLegs()</code> should be a function.
testString: assert(typeof(dog.sayLegs) === 'function');
- text: <code>dog.sayLegs()</code> should return the given string - note that punctuation and spacing matter.
testString: assert(dog.sayLegs() === 'This dog has 4 legs.');
Challenge Seed
let dog = {
name: "Spot",
numLegs: 4,
};
dog.sayLegs();
Solution
let dog = {
name: "Spot",
numLegs: 4,
sayLegs () {
return 'This dog has ' + this.numLegs + ' legs.';
}
};
dog.sayLegs();