javascript实现"类"

javascript基于对像,而不是面向对象,没有类的概念,但它的function可以定义“类”

一、定义类

var Animal = function(name) {
this.name = name;

        // 特权方法,创建实例对象时都会执行创建

this.setName = function(name) {this.name = name;};
this.getName = function() {return this.name};
};

// 原型方法只创建一次
Animal.prototype.getAniName = function () {
  return this.name;
};


二、继承

var Dog = function(name) {
    Animal.call(this, name);
};

(function(){

  // 制造原型链
  var Super = function(){};
  Super.prototype = Animal.prototype;
  Dog.prototype = new Super();
  Dog.prototype.getDogName = function() {
  return this.name;
  };
})();

var d1 = new Dog("jinmao");
console.log(d1.getAniName()); // jinmao
console.log(d1.getDogName());// jinmao
console.log(d1.getName());// jinmao
console.log(d1 instanceof Animal);// true
console.log(d1 instanceof Dog); // true



// 继续继承
var PetDog = function(name) {
    Dog.call(this, name);
};
(function(){
  var Super = function(){};
  Super.prototype = Dog.prototype;
  PetDog.prototype = new Super();
  PetDog.prototype.getPetName = function() {
  return this.name;
  };
})();


d1 = new PetDog("JingBa");
console.log(d1.getAniName()); // JingBa
console.log(d1.getDogName());// JingBa
console.log(d1.getName());// JingBa

console.log(d1.getPetName());// JingBa
console.log(d1 instanceof Animal);// true
console.log(d1 instanceof Dog); // true
console.log(d1 instanceof PetDog); // true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值