javascript实现"类"

来源:互联网 发布:ida软件安卓 编辑:程序博客网 时间:2024/06/10 04:25

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

0 0
原创粉丝点击