JS继承和闭包

一 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都是闭包,因为它总是能访问在它外部定义的数据。

闭包可以用在许多地方。它的最大用处有两个,一个是前面提到的可以读取函数内部的变量,另一个就是让这些变量的值始终保持在内存中

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值