在JavaScript中实现继承的方法:
- 原型链(prototype chaining)
- call()/apply()
- 混合方式(prototype和call()/apply()结合)
- 对象冒充
继承的方法如下:
1、prototype原型链方式:
function car(price){
this.price = price;
}
car.prototype.sayPrice = function(){
console.log("Price is "+this.price);
}
var oCar = new car("100W");
oCar.sayPrice();
function toyCar(price){
this.price = price;
}
toyCar.prototype = new car()
var oCar2 = new toyCar("10CNY");
oCar2.sayPrice();
2、call()/apply()方法
function useCall(a,b){
this.a = a;
this.b = b;
this.say = function(){
console.log("I'm "+this.a+" You're "+this.b);
}
}
function callThefunction (){
var args = arguments;
useCall.call(this,args[0],args[1]);
// useCall.apply(this,arguments);
}
var testCall1 = new useCall("Not YY","Not TT");// I'm Not YY You're Not TT
testCall1.say();
var testCall2 = new callThefunction("YY","TT");// I'm YY You're TT
testCall2.say();
3、混合方法【prototype,call/apply】
function house(size,price){
this.size = size;
this.price = price;
}
house.prototype.showArea=function (){
console.log("面积为"+this.size);
}
house.prototype.sayPrice=function (){
console.log("价钱为"+this.price);
}
function maofan(size,price){
house.call(this,size,price);
}
maofan.prototype = new house();
var newmaofan = new maofan("20Square meters ","1000CNY");
newmaofan.showArea();
4、对象冒充
function Person(name,age){
this.name = name;
this.age = age;
this.show = function(){
console.log(this.name+", "+this.age);
}
}
Person.prototype.sayHi = function(){
alert('hi');
}
function Student(name,age){
this.student = Person; //将Person类的构造函数赋值给this.student
this.student(name,age); //js中实际上是通过对象冒充来实现继承的
delete this.student; //移除对Person的引用
}
var s = new Student("小明",17);// 小明,
s.show();
var p = new Person("小花",18);// 小花
p.show();