js:prototype

来源:互联网 发布:jsp写java代码 编辑:程序博客网 时间:2024/06/08 17:06

So we know that a class will have certain properties and methods, but what keeps track of what a given class can or can't do? What a class has or doesn't have? That is the job of the prototype.

JavaScript automatically defines the prototype for class with a constructor. For example, our Dog constructor ensures that the Dog prototype has abreed property. Remember, the Dogprototype keeps track of what Dog has, doesn't have, can, or can't do.

Example:

function Dog (breed) {
  this.breed = breed;
}


// here we make buddy and teach him how to bark
var buddy = new Dog("Golden Retriever");
buddy.bark = function() {
  console.log("Woof");
};
buddy.bark();


// here we make snoopy
var snoopy = new Dog("Beagle");
// we need you to teach snoopy how to bark here


// this causes an error, because snoopy doesn't know how to bark!
snoopy.bark();

0 0