第一個例子:理解JavaScript類的方法和原型
function Animal(name) {
// Instance properties can be set on each instance of the class
this.name = name;
this.speak = function() {
console.log("My name is " + this.name);
}
}
var animal = new Animal('Petname1');
animal.speak();
function Cat(name) {
Animal.call(this, name);
}
Cat.prototype = new Animal();
var cat = new Cat('Petname2');
console.log(cat.speak());
第二個例子:
function Animal(name) {
// Instance properties can be set on each instance of the class
this.name = name;
}
Animal.prototype.speak = function() {
console.log("My name is " + this.name);
};
var animal = new Animal('Petname1');
animal.speak();
function Cat(name) {
Animal.call(this, name);
}
Cat.prototype = new Animal();
var cat = new Cat('Petname2');
console.log(cat.speak());
在第一示例中,我直接添加到類,在我通過將第二示例prototype
。有什麼不同?輸出是一樣的。
http://blog.slaks.net/2013-09-03/traditional-inheritance-in-javascript/ – SLaks
我沒有在任何地方看到「Monty''字符串。 – MinusFour