面向对象编程:了解自己的属性
请看下面的实例,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); // prints [ "name", "numLegs" ]
将canary对象里面的自身属性添加到ownProps数组里面。
function Bird(name) {
this.name = name;
this.numLegs = 2;
}
let canary = new Bird("Tweety");
let ownProps = [];
// 请把你的代码写在这条注释以下
for (let property in canary) {
if(canary.hasOwnProperty(property)) {
ownProps.push(property);
}
}
hasOwnProperty函数:
语法:object.hasOwnProperty(property)
返回一个布尔值,判断对象是否包含特定的自身(非继承)属性。
- for (let property in canary):遍历