Files
freeCodeCamp/curriculum/challenges/ukrainian/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-own-properties.md
2023-07-24 08:34:47 -07:00

2.4 KiB
Raw Blame History

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
587d7dae367417b2b2512b7b Власні властивості 1 301326 understand-own-properties

--description--

У цьому прикладі конструктор Bird визначає властивості name та numLegs:

function Bird(name) {
  this.name = name;
  this.numLegs = 2;
}

let duck = new Bird("Donald");
let canary = new Bird("Tweety");

name та numLegs називаються власними властивостями, оскільки їх визначено одразу в екземплярі об’єкта. Це означає, що duck та canary мають власні копії властивостей. Кожен екземпляр Bird матиме власну копію властивостей. Цей код додає всі власні властивості duck до масиву ownProps:

let ownProps = [];

for (let property in duck) {
  if(duck.hasOwnProperty(property)) {
    ownProps.push(property);
  }
}

console.log(ownProps);

Консоль показуватиме значення ["name", "numLegs"].

--instructions--

Додайте власні властивості canary до масиву ownProps.

--hints--

ownProps має містити значення numLegs та name.

assert(ownProps.indexOf('name') !== -1 && ownProps.indexOf('numLegs') !== -1);

Виконайте це завдання, не використовуючи вбудований метод Object.keys().

assert(!/Object(\.keys|\[(['"`])keys\2\])/.test(code));

Виконайте це завдання, не закодовуючи масив ownProps жорстко.

assert(
  !/\[\s*(?:'|")(?:name|numLegs)|(?:push|concat)\(\s*(?:'|")(?:name|numLegs)/.test(
    code
  )
);

--seed--

--seed-contents--

function Bird(name) {
  this.name = name;
  this.numLegs = 2;
}

let canary = new Bird("Tweety");
let ownProps = [];
// Only change code below this line

--solutions--

function Bird(name) {
  this.name = name;
  this.numLegs = 2;
}

let canary = new Bird("Tweety");
function getOwnProps (obj) {
  const props = [];

  for (let prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      props.push(prop);
    }
  }

  return props;
}

const ownProps = getOwnProps(canary);