20151028 继承
继承(方法)
一、对象冒充
原理:让父类的构造函数成为子类的方法,通过this关键字给所有属性和方法赋值。
function Person(name,age) {
this.name = name;
this.age = age;
this.sayName = function() {
console.log(this.name);
}
}
function Student(name,age) {
this.obj = Person;
this.obj(name,age);
delete this.obj;
}
var s1 = new Student("zhangsan","32")
console.log(s1.name); //输出: zhangsan
console.log(s1.age); //输出: 32
s1.sayName(); //输出: zhangsan
二、call和apply的方法
每个对象都有call的方法。——原理还是同象冒充方式一样。
function Person(name,age) {
this.name = name;
this.age = age;
this.sayName = function() {
console.log(this.name);
}
}
function Student(name,age,sex) {
//Person.apply(this,[name,age]);
Person.call(this,name,age); 【注意传参方式】
this.sex = sex;
}
var stal = new Student("zhangsan", 23, "nan");
console.log(stal.name);
console.log(stal.age);
console.log(stal.sex);
stal.sayName();
//call和apply两种方式:
Person.call(this,name,age);
Person.apply(this,[name,age]);【注意传参方式】
三、原型链的继承方式
原理:使子类原型对象指向父类的实例以实现继承,即重写类的原型.
原型链的方式不能实现传参.
//父类
function Person(name,age) {
this.name = name;
this.age = age;
this.sayName = function() {
console.log(this.name);
};
}
//子类
function Student(name,age) {
this.constructor(name,age); //通过父类的构造器对属性进行初始化
this.sex = "male";
}
Student.prototype = new Person; //子类通过原型的方式获得父类对象中的属性
var a = new Student("zhang",23);
console.log(a.name);
代码片段:
Object.prototype.name = "zhangsan";
Object.prototype.sayName = function() {
console.log(this.name);
}
function groundfather() {
}
groundfather.prototype = new Object();
console.log(groundfather.prototype); //输出: Object {name: "zhangsan", sayName: function}
function father() {
}
father.prototype = new groundfather();
console.log(father.prototype); //输出:groundfather {name: "zhangsan", sayName: function}
function son() {
}
son.prototype = new father();
console.log(son.prototype); //输出:father {name: "zhangsan", sayName: function}
var f1 = new son();
console.log(f1.name); //输出: zhangsan
console.log(f1.sayName);
//输出: function () {
console.log(this.name);
}
[依次往上找]
四、混合继承模式的继承方式 ——提高内存使用率
原理: 混合call和原型链
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayName = function () {
console.log(this.name);
};
function Student(name, age, sex) {
Person.call(this, name, age);
this.sex = sex;
}
Student.prototype = new Person();
var stu = new Student("zhangsan", 21, "男");
console.log(stu.name, stu.age, stu.sex);
stu.sayName();