javascript内部原理篇[javascript实现继承]
2014-01-01 15:28 低调de草原狼 阅读(134) 评论(0) 收藏 举报javascript的面向对象并非新鲜事务,现在简单模拟OOP实现继承
/**
* 继承
*/
(function(){
//创建一个人员类
function Person(name){
this.name = name;
}
//创建一个Teacher类
function Teacher(name, books){
//call方法可以让一个函数的对象上下文从初始化变为由this来决定
//调用Person的构造函数,因为Person没用new 所以是个空对象
//相当于java中的super函数
Person.call(this, name);
this.books = books;
}
/**
* 创建extend函数为了所有的继承操作
*/
function extend(subClass, superClass){
//叫子类原型类属性等于父类原型类属性
subClass.prototype = new superClass();
subClass.prototype.constructor = subClass;
//为了以后能够方便调用,也就是说在不知父类名称的情况下,可以直接调用
//我们增加以下语句
subClass.superClass = superClass.prototype;
}
function Author(name,books){
//Author.superClass.constructor.call(this,name);
//继承,将name属性的赋值方式在本类中继承
Author.superClass.constructor.call(this,name);
//Person.call(this,name);
this.books = books;
this.getBook = function(){
return this.name +" "+ this.books;
}
}
extend(Author, Person);
var peter = new Author("123","JAVASCIPT");
alert(peter.getBook())
})();
浙公网安备 33010602011771号