1.js原型(prototype)实现继承
function person(name, age) {
this.name = name;
this.age = age;
this.child = [1,2];
}
person.prototype.say = function() {
alert("使用原型得到Name:" + this.name)
}
//var per = new person("cherry", 22);
//per.say();
function Student() {}
Student.prototype = new person("cherryStu", 23);//原型继承person类并初始化,不可多重继承
Student.prototype.grade = 3;//定义新的属性
Student.prototype.init = function() { //定义新的方法
alert(this.child);
}
var stu = new Student();
//stu.say(); //父类方法可以调用
stu.init(); //1,2
var stu2 = new Student(); //缺点:当有子类有多个实例时,其中一个实例改变父类中的属性值,其他子类跟着变化
stu.child.push(3);
stu2.init();//1,2,3
stu.init();//1,2,3
2.构造函数实现继承
function Parent(name){
this.name=name;
this.sayParent = function() {
alert("Parent:"+this.name);
}
}
//缺点:父类方法如改成这样定义,则子类在用构造函数继承时不能调用
//Parent.prototype.sayParent = function() {
// alert("Parent:"+this.name);
//}
function Child(name, age) {
this.tempMethod = Parent; //tempMethod为自定义名字, 这里使用了构造函数继承 对象冒充
this.tempMethod(name);
this.age = age;
this.sayChild = function() {
alert("Child:" + this.name + " age:" + this.age);
}
}
var par = new Parent("Father");
par.sayParent();
var child = new Child("Lucy", 22);
child.sayChild();
3.call , apply实现继承
function Person(name, age, love) {
this.name = name;
this.age = age;
this.love = love;
this.say = function say() {
alert("姓名:" + name + " 年龄:" + age + " 爱人:" + love);
}
}
function Student(name, age) {
Person.call(this, name, age);
}
function Teacher(name, age) {
Person.apply(this, [name, age]);
}
var per = new Person("武凤楼", 25, "魏荧屏");
per.say();
var stu = new Student("曹玉", 18);
stu.say();
var tea = new Teacher("秦杰", 16);
tea.say();
4.原型继承和构造函数继承混合