js继承的日志
1.原型继承/*extend函数,实现原型式继承*/
var extend = function(obj){
if(typeof obj !== 'object'){
throw new Error('fatal error: "Object.prototype.extend" expects a object');
}
var F = function(){}; //创建一个中间函数对象
F.prototype = obj; //设置其原型对象指向obj
return new F();//返回实例化的F
};
/*父类字面量对象*/
var Person = {
init: function(name){//初始化函数,进行各种属性设置,代替了构造函数的作用
this.name = name;
},
getName:function(){
return this.name;
}
};
/*子类对象*/
var author1 = extend(Person);//继承Person
author1.init('author');
alert(author1.getName()); //输出author
author1.books = 'xxx'; //设置自己的属性
author1.getBooks = function(){
return this.books;
};
alert(author1.getBooks());//输出xxx
2.类式继承
/*给函数原型增加一个extend函数,实现继承*/
Function.prototype.extend = function(superClass){
if(typeof superClass !== 'function'){
throw new Error('fatal error:Function.prototype.extend expects a
constructor of class');
}
var F = function(){}; //创建一个中间函数对象以获取父类的原型对象
F.prototype = superClass.prototype; //设置原型对象
this.prototype = new F(); //实例化F, 继承父类的原型中的属性和方法,而无需调用父类的
构造函数实例化无关的父类成员
this.prototype.constructor = this; //设置构造函数指向自己
this.superClass = superClass; //同时,添加一个指向父类构造函数的引用,方便调用父类
方法或者调用父类构造函数
return this;
};
/*Class Person*/
function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name;
};
/*Class Author*/
function Author(name, books){
Author.superClass.call(this, name);
this.books = books;
}
/*
* 这里用了链式调用,下面语句等价于:
* Author.extend(Person); Author.prototype.getBooks = function(){```};
*/
Author.extend(Person).prototype.getBooks = function(){
return this.books;
};
/*方法的覆写,通过superClass调用父类的方法获得基本信息,再调用子类的方法获得更特殊的信息*/
Author.prototype.getName = function(){
var name = Author.superClass.prototype.getName.call(this);
return name + ', Author of ' + this.getBooks();
};
var person = new Author("小白", "javascript高级编程");
alert( person.getName() );
3.js对象“属性”和“方法”的测试
function A(){};
A.prototype.getName = function(){
return this.name;
}
A.prototype.setName = function(name){
this.name = name;
}
function B(){};
B.prototype.getAge = function(){
return this.age;
}
B.prototype.setAge = function(age){
this.age = age;
}
A.prototype = new B();//是克隆,覆盖了A的原型
var test = new A;
test.setAge(123);
for(var p in test){
if((typeof test[p]) == "function"){
alert(p);
alert(test[p]);
console.log("方法");
} else {
alert(p);
alert(test[p]);
console.log("属性");
}
}