mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-01-26 03:02:39 -05:00
2.2 KiB
2.2 KiB
id, title, localeTitle, challengeType
| id | title | localeTitle | challengeType |
|---|---|---|---|
| 587d7dad367417b2b2512b75 | Create a Method on an Object | Crear un método en un objeto | 1 |
Description
Objects pueden tener un tipo especial de property , llamado method .
Methods son properties que son funciones. Esto agrega un comportamiento diferente a un object . Aquí está el ejemplo de duck con un método:
let duck = {El ejemplo agrega el
name: "Aflac",
numLegs: 2,
sayName: function() {return "The name of this duck is " + duck.name + ".";}
};
duck.sayName();
// Returns "The name of this duck is Aflac."
method sayName , que es una función que devuelve una oración que da el nombre del duck .
Observe que el method accedió a la propiedad de name en la declaración de retorno usando duck.name . El próximo desafío cubrirá otra forma de hacer esto.
Instructions
object dog , dale un método llamado sayLegs . El método debe devolver la frase "Este perro tiene 4 patas".
Tests
tests:
- text: <code>dog.sayLegs()</code> debería ser una función.
testString: 'assert(typeof(dog.sayLegs) === "function", "<code>dog.sayLegs()</code> should be a function.");'
- text: <code>dog.sayLegs()</code> debe devolver la cadena dada; tenga en cuenta que la puntuación y el espaciado son importantes.
testString: 'assert(dog.sayLegs() === "This dog has 4 legs.", "<code>dog.sayLegs()</code> should return the given string - note that punctuation and spacing matter.");'
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();