Dav*_*ang 56
简单来说,继承是获得其他东西的属性或行为的一件事的概念.要说A 继承自B,就是说A 是 B的一种类型 .An Bird 继承自Animal,因为Bird 是一种动物 - 它可以做同样的事情,但更多(或不同)!
在JavaScript中,这种关系有点复杂,但要遵循语法.您必须使用一个特殊对象prototype,该对象将属性分配给诸如Animal之类的类型.只有functions有一个prototype,这就是你必须先创建一个函数的原因:
function Animal() {}; // This is the Animal *Type*
Animal.prototype.eat = function () {
alert("All animals can eat!");
};
Run Code Online (Sandbox Code Playgroud)
现在要创建一个继承自Animal 的类型,您也可以使用该prototype对象,但这次是属于另一个类型的对象,例如Bird:
function Bird() {}; // Declaring a Bird *Type*
Bird.prototype = new Animal(); // Birds inherit from Animal
Bird.prototype.fly = function() {
alert("Birds are special, they can fly!");
};
Run Code Online (Sandbox Code Playgroud)
这样做的结果是你创建的任何鸟类(称为鸟类的实例)都具有动物的属性,但它们还有额外的.fly():
var aBird = new Bird(); // Create an instance of the Bird Type
aBird.eat(); // It should alert, so the inheritance worked
aBird.fly(); // Important part of inheritance, Bird is also different to Animal
var anAnimal = new Animal(); // Let's check an instance of Animal now
anAnimal.eat(); // Alerts, no problem here
anAnimal.fly(); // Error will occur, since only Birds have fly() in its prototype
Run Code Online (Sandbox Code Playgroud)
sgo*_*les 13
一个很好的解释由罗伯特在继承的Javascript 这里
继承在JavaScript中的工作方式是prototype,而不是class-based.
例如
function Being () {
this.living = true;
}
Being.prototype.breathes = function () {
return true;
Run Code Online (Sandbox Code Playgroud)
继承Being的对象
Robert.prototype = new Being;
function Robert () {
this.blogs = true;
}
Robert.prototype.getsBored = function () {
return "You betcha";
};
Run Code Online (Sandbox Code Playgroud)
所以,基本上,如果我们创建一个Robert对象的新实例并调用它的一些方法,结果将是:
// Create an instance of the Robert object
var me = new Robert();
/*
Returns "You betcha" as it's a method
belonging to the Robert object
*/
me.getsBored();
/*
Returns true. Since the Robert object
doesn't have a breathes method of
its own, it goes back in the
prototype chain to its parent
object, Being, and finds the
method there
*/
me.breathes();
Run Code Online (Sandbox Code Playgroud)
同时也很好地阅读了JavaScript继承:JavaScript继承
很简单,您可以从另一个 javascript 对象继承属性,如下所示:
var a = function () {}
a.prototype.sayHello = function () { alert('hello') }
var b = function () {}
b.prototype = new a();
var c = new b();
c.sayHello(); // Alerts "hello"
Run Code Online (Sandbox Code Playgroud)
jQuery 的 John Resig 有一个关于继承的优秀指南http://ejohn.org/apps/learn/ http://ejohn.org/apps/learn/#76
编辑根据罗伯茨评论更新了代码。