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

javascript继承

2015-11-30 22:02 651 查看

javascript的继承

在js设计之初,作者就没有想到这门语言会这门广泛的应用,但当此时已经广泛应用之后,发现js存在很多不足,它没有类的概念,不能像其他OO语言一样,实现继承, 只能通过原型链,去克隆另外一个类的属性,假装在继承。具体是用来干嘛呢?
答案是:要是用来复用我们之前写过的方法功能等等。比如我想要一个之前写过的方法,如果去copy,就会觉得很麻烦,如果可以直接继承过来,不就省事很多了吗?

好!接下来,来说说js继承是怎么实现的?
答案是:想办法把某个对象的属性复制到自己要用的对象中,从而让自己的对象可以复用那个对象的属性,这就是继承。

现在来说说继承的方法(了解继承之前,要先了解一下js的原型链,以及call和apply这个回调函数的作用)。
js的继承有两种方式:1、[b]call、apply实现继承;2、原型链实现继承。[/b]

1、call、apply实现继承,这一种方法也是最为简单,讲父对象的构造函数绑定在子对象上。

var A=function(){
this.name="meili";
this.show=function(){
alert(this.color);
}
}
var B=function(){
this.color="red" ;
A.call(this)//a在 b中执行,实现了B继承A得功能
}

var C = new B();  //创建了对象A,并且克隆了函数B的所有属性,然而B已经继承了A,从而C也拥有了A的属性。
C.show();  //red


  补充:还有一个apply函数的继承,原理和call函数一样,具体请看.call()和.apply()的相同点和不同点

2、原型链实现继承

1)基本模式:

function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.sayHello=function(){
alert("使用原型得到Name:"+this.name);
}
var per = new Person("alin",21);
per.sayHello(); //输出:使用原型得到Name:alin


解析:前4行定义了一个Person(),第5行往Person的原型链表上添加了sayHello的属性函数,第8行,创建新对象per,并且该对象克隆了Person的所有属性(sayHello是Person中的属性了),所以,第9行就可以直接调用了。

2)prototype原型模式:

普通版:

function Person(name){
this.name = name;
}

function Student(species,age){
this.species = species;
this.age = age;
}

Student.prototype = new Person();
Student.prototype.constructor = Student;
var studentalin = new Student("大学生",21);
console.log(studentalin.species);//大学生


封装版:

function Person(name){
this.name = name;
}

function Student(species,age){
this.species = species;
this.age = age;
}

function extend(Child,Parent){
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}

extend(Student,Person);
var studentalin = new Student("大学生",21);
console.log(studentalin.species);//大学生


 说明:这个封装版,是YUI库实现继承的方法。

拷贝版:

function Person(name){
this.name = name;
}

function Student(species,age){
this.species = species;
this.age = age;
}

function extend(Child,Parent){
var p = Parent.prototype;
var c = Child.prototype;
for(var i in p){
c[i] = p[i];
}
c.uber = p ;
}

extend(Student,Person);
var studentalin = new Student("大学生",21);
console.log(studentalin.species);//大学生


  说明:把子对象的所有属性都拷贝到父对象中。

最后题外了解一下function创建的原理:

var A = function(){};

分解一下,上面创建 A() 的原理:
1、x = new Object();//开辟一块内存,然后创造一个对象
2、x.constructor = A;//将x的构造函数指向A的函数实体
3、A.prototype = x;//A的原型指向新开辟的对象

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: