JS初步继承机制.
2010-04-13 10:40 BlueDream 阅读(929) 评论(0) 编辑 收藏 举报JS继承分为:类式继承和原型式继承.
类式继承源于大多程序员熟知的传统形式.所以比较容易接受. 原型式继承是源于JS独特的原型机制.因此效率更高.至于哪一种还是看个人习惯了.
这里只是构造了个简单的类式继承的原型.
function inherit(subclass, superclass) { // 建立空的构造器.避免了superclass的实例化. var F = function() {}; F.prototype = superclass.prototype; subclass.prototype = new F(); // 重置原型链 subclass.prototype.constructor = subclass; // 松耦合实例继承.并保证superclass的构造器指向正确 subclass.superclass = superclass.prototype; if(superclass.prototype.constructor == Object.prototype.constructor) { superclass.prototype.constructor = superclass; } } /* superclass */ function Person( name ) { this.name = name; }; Person.prototype.getName = function() { return this.name; }; /* subclass */ function Author( name, books ) { // 这样就可以和Person耦合松散. Author.superclass.constructor.call(this, name); this.books = books; }; inherit(Author, Person); Author.prototype.getBooks = function() { return this.books; } var a = new Author('kc', 'dd'); alert(a.getName()) </script>
上面的例子就是Author继承了Person类