您的位置:首页 > Web前端 > JavaScript

javascript 继承机制

2014-04-24 18:50 357 查看
<script type="text/javascript">

/*对象继承机制*/

/*----------------------------构造函数绑定----------------------------*/

function Animal(){

this.species="动物";

}

function Cat(name,color){

Animal.apply(this,arguments);

this.name=name;

this.color=color;

}

/*var cat1=new Cat("猫","yellow");

console.log(cat1.species+'----------构造函数绑定');*/

/*----------------------------prototype 对象继承---------------------------*/

Cat.prototype=new Animal();

Cat.prototype.constructor=Cat;

console.log(Cat.prototype.constructor==Cat);

var cat2=new Cat('dog','red');

console.log(cat2.constructor);/*每个实例也有也有一constructor 属性,默认调用prototype对象的contructor属性。*/

console.log(cat2.species);

/*----------------------------prototype 对象继承2---------------------------*/

function Animal2(){

};

function Dog(name){

this.name=name;

}

Animal2.prototype.species='动物 2';

Dog.prototype=Animal2.prototype;

Dog.prototype.constructor=Dog;

var dog=new Dog("dog1");

console.log(dog.constructor);

console.log(dog.species+'------------');

/*---------------------------- 空对象作为介质 对象继承---------------------------*/

function Animal3(){

};

Animal3.prototype.species='动物 3';

function F(){};

F.prototype=Animal3.prototype;

Dog.prototype=new F();

Dog.prototype.constructor=Dog;

var dog2=new Dog('dog2');

console.log(dog2.species);

/*可以将上面方法封装成一个函数*/

function extend(Parent,Child){

var F=function(){};

F.prototype=Parent.prototype;

Child.prototype=new F();

Child.prototype.constructor=Child;

Child.uber=Parent.prototype;

};

extend(Animal3,Dog);

var dog3=new Dog('dog3');

console.log(dog3.species+'-----extend 方法实现');
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: