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"]

运行结果

 在线测试

发布了56 篇原创文章 · 获赞 1 · 访问量 818

猜你喜欢

转载自blog.csdn.net/weixin_44790207/article/details/105056887