11.迭代所有属性

说明

你现在已经了解到了两种属性:own属性和prototype属性。own属性直接在对象实例上定义。而prototype属性是在prototype上定义。

function Bird(name) {
  this.name = name;//own property
}

Bird.prototype.numLegs = 2; // prototype property

var duck = new Bird("Donald");

以下是将duckown属性添加到数组的ownProps以及将prototype属性到数组的prototypeProps

var ownProps = [];
var 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"]


练习

beagle的所有own属性添加到数组的ownProps。将Dog的所有prototype属性添加到数组的prototypeProps中。

  • ownProps应该包含属性"name"
  • prototypeProps应该包含属性"numLegs"
  • 完成这个挑战不能构建 Object.keys().

答案

方法描述
this当前执行代码的环境对象
prototype向对象添加属性和方法。
let声明一个块级作用域的本地变量,并且可选的将其初始化为一个值。
new创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。
for...in用于遍历数组或者对象的属性(对数组或者对象的属性进行循环操作)。
console.log()用于在控制台输出信息(浏览器按下 F12 打开控制台)。
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 
for (let property in beagle) {
  if(beagle.hasOwnProperty(property)) {
    ownProps.push(property);
  } else {
    prototypeProps.push(property);
  }
}


console.log(ownProps); // prints ["name"]
console.log(prototypeProps); // prints ["numLegs"]

运行结果

 在线测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值