原型继承
JavaScript的原型继承实现方式就是:
-
定义新的构造函数,并在内部用
call()调用希望“继承”的构造函数,并绑定this; -
借助中间函数
F实现原型链继承,最好通过封装的inherits函数完成; -
继续在新的构造函数的原型上定义新方法。
我们让teacher继承student
function student(name) {
this.name = name || "ss";
}
}
function teacher(props) {
student.call(this, props); //关键
this.techername="lll";
}
function f() { //空函数用于桥接
student.call(this, props); //关键
this.techername="lll";
}
function f() { //空函数用于桥接
}
f.prototype = student.prototype;
teacher.prototype = new f();
teacher.prototype.constructor=teacher; //将teacher的原型构造函数指向自己
f.prototype = student.prototype;
teacher.prototype = new f();
teacher.prototype.constructor=teacher; //将teacher的原型构造函数指向自己
teacher.prototype.showname = function () {
console.log(this.name,this.techername)
}
console.log(this.name,this.techername)
}
var xiaoming = new teacher("小明");
xiaoming.showname(); //小明
console.log(xiaoming.__proto__);//student
console.log(xiaoming.__proto__.constructor);//f teacher
xiaoming.showname(); //小明
console.log(xiaoming.__proto__);//student
console.log(xiaoming.__proto__.constructor);//f teacher
*封装
function inherits(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}

浙公网安备 33010602011771号