freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../object-oriented-programming/create-a-method-on-an-objec...

2.0 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7dad367417b2b2512b75 Create a Method on an Object 1 在对象上创建方法

Description

Objects可以具有特殊类型的property ,称为methodMethods是作为函数的properties 。这会为object添加不同的行为。这是一个方法的duck示例:
让duck = {
名称“Aflac”
numLegs2
sayNamefunction{return“这个鸭子的名字是”+ duck.name +“。”;}
};
duck.sayName;
//返回“这个鸭子的名字是Aflac。”
该示例添加了sayName method ,该method是一个返回给出duck名称的句子的函数。请注意,该method使用duck.name访问return语句中的name属性。下一个挑战将包括另一种方法。

Instructions

使用dog object ,给它一个名为sayLegs的方法。该方法应该返回句子“这条狗有4条腿”。

Tests

tests:
  - text: <code>dog.sayLegs()</code>应该是一个函数。
    testString: 'assert(typeof(dog.sayLegs) === "function", "<code>dog.sayLegs()</code> should be a function.");'
  - text: <code>dog.sayLegs()</code>应返回给定的字符串 - 请注意标点符号和间距很重要。
    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

// solution required