JS继承和闭包
一 JS如何实现继承?
JavaScript中继承方式主要(常用到的)有:call,apply,原型链、混合方式;
call和apply作用都是把一个对象绑定到另外一个对象。
代码:
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}
c.m1();//error
原型链继承
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继承属性+原形链接继承方式
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
<!--以上内容转载自http://qiqicartoon.com/?p=58 -->
二 JS中闭包概念
闭包的定义:(官方)它是一个拥有许多变量和绑定了这些变量的环境的表达式(通常是一个函数),因而这些变量也是该表达式的一部分。闭包的两个特点:
1、作为一个函数变量的一个引用 – 当函数返回时,其处于激活状态。
2、一个闭包就是当一个函数返回时,一个没有释放资源的栈区
雅虎前端工程师(YUI开发者)的解释:闭包是通过在对一个函数调用的执行环境中返回一个函数对象构成的。比如,在对函数调用的过程中,将一个对内 部函数对象的引用指定给另一个对象的属性。或者,直接将这样一个(内部)函数对象的引用指定给一个全局变量、或者一个全局性对象的属性,或者一个作为参数 以引用方式传递给外部函数的对象

浙公网安备 33010602011771号