一 JS如何实现继承?
JavaScript中继承方式主要(常用到的)有:call,apply,原型链、混合方式;
call和apply作用都是把一个对象绑定到另外一个对象。 代码:
1
2
3
4
5
6
7
function a(name,age){
this.name = name;
this.age = age;
}
function b(){
a.call(this,)
}
apply方法和call几乎一样,唯一区别是参数传递的方法,apply方法要求参数必须以数组的形式传递 a.apply(this,[name,age]); 这两个方法的构造函数的prototype属性定义的方法不能够继承 a.prototype.m1 = function (){return this.age} b.m1();//error
原型链继承
1
2
3
4
5
6
7
8
9
10
11
12
13
function a(){
}
a.prototype.name = '阿里巴巴';
a.prototype.age = 10;
a.prototype.getName = function (){return this.name}
a.prototype.getAge = function (){return this.age}
function b(){}
b.prototype = new a()
var c = new b;
alert(c.getName())//阿里巴巴
alert(c instanceof b)//true
alert(c instanceof a)//true
使用原型链接继承时一定要确保构造函数没有参数
混合方式 混合方式=call/apply继承属性+原形链接继承方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function a(name,age){
this.name = name;
this.age = age;
}
a.prototype.getName = function (){return this.name}
a.prototype.getAge = function (){return this.age}
function b(name,age){
a.apply(this,[name,age]);
}
b.prototype = new a();
var c = new b();
c.name = '阿里巴巴';
c.age = 10;
alert(c.getAge());//10
alert(c.getName());//阿里巴巴
alert(c instanceof b)//true
alert(c instanceof a)//true<br><br><!--以上内容转载自http://qiqicartoon.com/?p=58 --><br><br>二 JS中闭包概念
闭包
如果一个函数访问了它的外部变量,那么它就是一个闭包。在本质上,闭包就是将函数内部和函数外部连接起来的一座桥梁。从技术上来讲,在JS中,每个function都是闭包,因为它总是能访问在它外部定义的数据。
闭包可以用在许多地方。它的最大用处有两个,一个是前面提到的可以读取函数内部的变量,另一个就是让这些变量的值始终保持在内存中。