2.4 KiB
2.4 KiB
id, challengeType, forumTopicId, localeTitle
id | challengeType | forumTopicId | localeTitle |
---|---|---|---|
587d7daf367417b2b2512b7d | 1 | 301320 | 迭代所有属性 |
Description
自身
属性和原型
属性。自身
属性是直接在对象上定义的。而原型
属性是定义在prototype
上的:
function Bird(name) {
this.name = name; // 自身属性
}
Bird.prototype.numLegs = 2; // 原型属性
let duck = new Bird("Donald");
这个示例会告诉你如何将duck
的自身
属性和原型
属性分别添加到ownProps
数组和prototypeProps
数组里面:
let ownProps = [];
let prototypeProps = [];
for (let property in duck) {
if(duck.hasOwnProperty(property)) {
ownProps.push(property);
} else {
prototypeProps.push(property);
}
}
console.log(ownProps); // prints ["name"]
console.log(prototypeProps); // prints ["numLegs"]
Instructions
beagle
的自身属性都添加到ownProps
数组里面去。将Dog
的所有原型
属性添加到prototypeProps
数组中。
Tests
tests:
- text: "这个<code>ownProps</code>数组应该包含<code>'name'</code>这个值。"
testString: assert(ownProps.indexOf('name') !== -1);
- text: "这个<code>prototypeProps</code>数组应该包含<code>'numLegs'</code>这个值。"
testString: assert(prototypeProps.indexOf('numLegs') !== -1);
- text: 在不使用内置方法<code>Object.keys()</code>的情况下完成这个挑战。
testString: assert(!/\Object.keys/.test(code));
Challenge Seed
function Dog(name) {
this.name = name;
}
Dog.prototype.numLegs = 4;
let beagle = new Dog("Snoopy");
let ownProps = [];
let prototypeProps = [];
// Add your code below this line
Solution
function Dog(name) {
this.name = name;
}
Dog.prototype.numLegs = 4;
let beagle = new Dog("Snoopy");
let ownProps = [];
let prototypeProps = [];
for (let prop in beagle) {
if (beagle.hasOwnProperty(prop)) {
ownProps.push(prop);
} else {
prototypeProps.push(prop);
}
}