[英]can somebody explain me how inheritance works in javascript
有人可以向我解释一下继承是如何在javascript(JS)中工作的,我已经看过很多教程,但是我无法理解它正在实现什么。
我经历过的是:
console.log('Initialized..')
function Animal() {
this.species = "animal";
}
Animal.prototype.category = function (){
alert(this.species);
}
function Dog(){
this.Animal();
}
copyPrototype(Dog, Animal)
var d = new Dog();
d.category();
在我看来,这是http://www.letscodejavascript.com/v3/episodes/lessons_learned/12是了解理解试图使经典OOP在JavaScript中工作时所滥用的机制的最佳资源。
以下是当有人告诉我必须在JS中使用OOP时的操作。 这可能是我在某处在线购买的东西。 无论如何,这里是这样:
/// Make this script available somewhere
var extendsClass = this.extendsClass || function (d, b) {
function __inheritedProto() { this.constructor = d; }
__inheritedProto.prototype = b.prototype;
d.prototype = new __inheritedProto();
}
var Animal = (function() {
function Animal(data) {
this.value = data;
}
Animal.prototype.method = function() {
return this.value;
};
return Animal;
})();
var Dog = (function(_super) {
extendsClass(Dog, _super);
function Dog() {
_super.apply(this, arguments);
}
Dog.prototype.method2 = function() {
return this.value * 2; //do something else
};
return Dog;
})(Animal);
/// Create some instances
var animal = new Animal(1);
var dog = new Dog(2);
/// Call some methods
animal.method(); // 1
dog.method(); // 2
dog.method2();// 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.