首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

javascript 原形模式

2012-08-26 
javascript 原型模式?myNestedFunc function(){?????????? ???? returndate.getMilliseconds()???? ???

javascript 原型模式

?

myNestedFunc = function(){

?????????? ???? returndate.getMilliseconds();

???? ???? };

???? return {// revealing modular pattern

?????????? foo: myNestedFunc

???? }

}

?

?

?

Prototype Pattern

?

优点:

<!--[if !supportLists]-->l? <!--[endif]-->充分利用JavaScript内建特性

<!--[if !supportLists]-->l? <!--[endif]-->“Modularize”代码为了构建可重用代码

<!--[if !supportLists]-->l? <!--[endif]-->让变量和函数脱离全局作用域

<!--[if !supportLists]-->l? <!--[endif]-->函数在内存中只加载一次

<!--[if !supportLists]-->l? <!--[endif]-->通过prototype可能override函数

缺点:

<!--[if !supportLists]-->l? <!--[endif]-->this指针很容易混淆

<!--[if !supportLists]-->l? <!--[endif]-->Constructor脱离prototype定义

?

Prototype pattern结构

var Calculator =function(eq){//定义一个对象

???? this.eqCtl = document.getElementById(eq);?

}

?

Calculator.prototype= {//扩展对象原型链上的方法

???? add: function(x, y){//封装,不污染全局作用域

?????????? var val = x + y;

?????????? this.eqCtl.innerHTML = val;

???? }

}

?

var calc? = new Calculator(‘eqCtl’);

calc.add(2,2);

?

Prototype Pattern一般用在实现一个类的功能,这个类中有一些属性和操作,这些操作要访问这些属性的值,定义函数对象(可以理解为类的模板)时就是初始化属性值,然后通过原型链来定义操作,这些操作是针对所有后期被实例化的对象,这些操作只被内存加载一次,但是个个实例化对象的属性都是独占内存的。

?

?

<!--EndFragment-->

热点排行
Bad Request.