JavaScript 没有像 Java 等面向对象语言的 class
关键字用法, 和 class
最像的就是 function
了. 下面的代码相当于在 JavaScript 中定义了一个类:
function Base(arg){ var self = this; self.base = 1; self.name = 'base'; }
如果想新定义一个类 Child 继承 Base, 怎么办? JavaScript 又没有 extends
. 这时, 就要利用到 prototype
了.
function Child(arg){ var self = this; self.name = 'child'; } // 继承在这里发生了! Child.prototype = new Base(); Child.prototype.constructor = Child;
这时, 使用 Child 类就没有什么特殊的了:
var child = new Child(); alert(child.base + ', ' + child.name); // 1, child
你还可以封装一下:
function class_extend(child, base){ child.prototype = new base(); child.prototype.constructor = child; } class_extend(Child, Base);