13.将prototype更改为新对象

说明

到目前为止,你已经分别向prototype添加了多个属性:

Bird.prototype.numLegs = 2;

在添加多个属性之后,这将变得乏味。

Bird.prototype.eat = function() {
  console.log("nom nom nom");
}

Bird.prototype.describe = function() {
  console.log("我的名字是"+ this.name);
}

更有效的方法是将prototype设置为已经包含属性的新对象。这样一来,属性就可以一次性添加:

Bird.prototype = {
  numLegs:2,
  eat: function() {
    console.log("nom nom nom");
},
  describe: function() {
    console.log("我的名字是"+ this.name);
  }
};


练习

通过将prototype设置为新对象,将属性numLegs以及两个方法:eat()describe()添加到Dogprototype

  • 应将Dog.prototype设置为新对象。
  • Dog.prototype应具有numLegs属性。
  • Dog.prototype 应该有 eat()函数。
  • Dog.prototype 应该有 describe()函数。

答案

方法 描述
this 当前执行代码的环境对象
console.log() 用于在控制台输出信息(浏览器按下 F12 打开控制台)。
prototype 向对象添加属性和方法。
function Dog(name) {
this.name = name; 
}

Dog.prototype = {
// Add your code below this line
    numLegs : 4,
    eat: function(){
        console.log("nom nom nom");
    },
    describe: function(){
        console.log("我的名字是" + this.name);
    }
};
发布了56 篇原创文章 · 获赞 1 · 访问量 816

猜你喜欢

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