1.对象冒充
说明:让父类的构造函数成为子类的,如:
function Par(a,b){
this.name = a;
this.age = b;
this.sayName = function(){
console.log(this.name)
}
}
function Stu(a,b){
this.obj = Par;
this.obj(a,b);
delete this.obj //删除
}
2.原型链
访问一个对象时,先在基本属性中查找,如果没有,就沿着_proto_往上查找,这就是原型链。
不能传参数,每一个对象共享数据。
function Far(){
this.age = 14;
}
Far.prototype.name = "abc";
function Chi(){
}
Chi.prototype = new Far(); //原型链
var p1 = new Chi();
console.log(p1.name); //输出 abc
console.log(p1.age); //输出 14
3.call 和 apply
function Par(a,b){
this.name = a;
this.age = b;
this.sayName = function(){
console.log(this.name)
}
}
function Stu(a,b){
//Par.call(this,a,b) //call的方法
Par.apply(this,[a,b]) //apply的方法
}
4.混合模式
function Gra(a){
this.name = a
}
Gra.prototype.sayName = function (){
console.log("aaaa")
};
function Fa(b){
this.age = b;
}
Fa.prototype = new Gra(); //原型链继承Gra.prototype的 sayName函数
function Chi(a,b,c){
Gra.call(this,a); //通过call继承Gra函数的name属性
Fa.apply(this,[b]); //通过call继承Fa函数的age属性
this.sex = c;
}
Chi.prototype = new Fa(); //原型链继承Fa.prototype的 sayName函数
var p1 = new Chi("爷爷",88,"男");
console.log(p1.name); //输出 爷爷
console.log(p1.age); //输出 88
console.log(p1.sex); //输出 男
p1.sayName() //输出 aaaa