JavaScript简单继承

不少C#或C++开发人员习惯使用继承来开发项目,因此当他们想学习JavaScript语言时,第一个问题通常是:“我怎么在JavaScript中使用继承?”。javascript

实际上JavaScript使用了一种不一样于C#或C++的方法来建立面向对象语言。它是基于prototype的语言。原型概念代表行为是能够经过clone已经存在的对象来做为原型复用的。在JavaScript中每一个对象都有原型,它定义了一系列对象可使用的方法和成员。没有class,只有对象。每个对象能够做为另外一个对象的原型。java

这个概念是很是灵活的,咱们能够用它来模拟OOP继承。程序员

实现继承

让咱们想象咱们使用JavaScript建立这个层次机构:函数

 Implementing Inheritance

首先咱们能够简单地建立ClassA。由于没有明确的类,咱们只需建立一个函数定义一组行为:工具

var ClassA = function(){
    this.name = "class A";
}

使用new 关键字来实例化这个“类”:学习

var a = new ClassA();
ClassA.prototype.print = function(){
    console.log(this.name);
}

而后使用对象来使用它:this

a.print()

很简单,对吧?spa

完整的样式只用了8行代码:prototype

 

var ClassA = function() {
    this.name = "class A";
}

ClassA.prototype.print = function() {
    console.log(this.name);
}

var a = new ClassA();

a.print();

如今让咱们来建立类之间的“继承”。这个工具只作一件简单的事:克隆原型:code

var inheritsFrom = function(child, parent) {
    child.prototype = Object.create(parent,prototype);
};

奇迹发生了!经过clone原型,咱们将全部成员和函数传给新类。

因此若是咱们想添加第一个类的子类,只须要使用这段代码:

var ClassB = function() {
    this.name = "class B";
    this.surname = "I'm the child";
}

inheritsFrom(ClassB, ClassA);

因此ClassB继承了ClassA的print函数,因此下面代码是有效的:

var b = new ClassB();
b.print();

因此产生如下输出:

class B

咱们甚至能够覆盖ClassB的print函数:

ClassB.prototype.print = function(){
    ClassA.prototype.print.call(this);
    console.log(this.surname);
}

在这种状况下,输出是这样的:

class B 
I’m the child

这里的技巧是调用ClassA.prototype来获取print函数。因为call函数咱们能够对当前对象(this)调用基本函数。

建立ClassC是显而易见的:

var ClassC = function () {
    this.name = "class C";
    this.surname = "I'm the grandchild";
}

inheritsFrom(ClassC, ClassB);

ClassC.prototype.foo = function() {
    // Do some funky stuff here...
}

ClassC.prototype.print = function () {
    ClassB.prototype.print.call(this);
    console.log("Sounds like this is working!");
}

var c = new ClassC();
c.print();

输出:

class C 
I’m the grandchild 
Sounds like this is working!

总结

最后,我想说明JavaScript不是C#或C++。它有本身的哲学。若是你说C++或C#程序员,而且你真的很想了解JavaScript全部精华,我给你最好的提示:不要试图将你的语言复制到JavaScript。没有最好的语言或最差的语言。只是不一样的哲学!

连接: http://www.sitepoint.com/simple-inheritance-javascript/

相关文章
相关标签/搜索