javascript面向对象中继承实现?

在JavaScript中实现继承的方法:

  1. 原型链(prototype chaining)
  2. call()/apply()
  3. 混合方式(prototype和call()/apply()结合)
  4. 对象冒充
    继承的方法如下:
    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();
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值