作家
登录

Prototype的Class.create函数解析

作者: 来源:www.28hudong.com 2013-03-30 00:43:11 阅读 我要评论

复制代码 代码如下: /** * 一个设计精巧的定时执行器 * 首先由 Class.create() 创建一个 PeriodicalExecuter 类型, * 然后用对象直接量的语法形式设置原型。 * * 需要特别说明的是 rgisterCallback 方法,它调用上面定义的函数原型方法bind, 并传递自己为参数。 * 之所以这样做,是因为 setTimeout 默认总以 window 对象为当前对象,也就是说,如果 registerCallback 方法定义如下的话: * registerCallback: function() { * setTimeout(this.onTimerEvent, this.frequency * 1000); * } * 那么,this.onTimeoutEvent 方法执行失败,因为它无法访问 this.currentlyExecuting 属性。 * 而使用了bind以后,该方法才能正确的找到this,也就是PeriodicalExecuter的当前实例。 */ var PeriodicalExecuter = Class.create(); PeriodicalExecuter.prototype = { initialize: function(callback, frequency) { this.callback = callback; this.frequency = frequency; this.currentlyExecuting = false; this.registerCallback(); }, registerCallback: function() { setTimeout(this.onTimerEvent.bind(this), this.frequency * 1000); }, onTimerEvent: function() { if (!this.currentlyExecuting) { try { this.currentlyExecuting = true; this.callback(); } finally { this.currentlyExecuting = false; } } this.registerCallback(); } } 具体Class.create()背后做了什么,具体来看看Class的实现。 复制代码 代码如下: /** * 创建一种类型,注意其属性 create 是一个方法,返回一个构造函数。 * 一般使用如下 * var X = Class.create(); 返回一个类型,类似于 java 的一个Class实例。 * 要使用 X 类型,需继续用 new X()来获取一个实例,如同 java 的 Class.newInstance()方法。 * * 返回的构造函数会执行名为 initialize 的方法, initialize 是 Ruby 对象的构造器方法名字。 * 此时initialize方法还没有定义,其后的代码中创建新类型时会建立相应的同名方法。 */ var Class = { create: function() { return function() { this.initialize.apply(this, arguments); } } } Class.create实际上是返回一个函数,那么new的时候,做了些什么呢。参照MDN When the code new foo(...) is executed, the following things happen: A new object is created, inheriting from foo.prototype. The constructor function foo is called with the specified arguments and this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments. The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.) new的时候会执行该返回的函数,即执行this.initialize.apply(this, arguments); 此时的this就是新生成的对象,这也就是说了所有对象的初始化工作全部委托给initialize函数了。 ------- 这里为什么要把自己的initialize方法绑定到自己身上??

  推荐阅读

  基于jquery的弹出提示框始终处于窗口的居中位置(类似于alert弹出框的效果)

原理很简单: 获取当前屏幕(窗体)的宽度和高度,因为不同浏览器的窗体大小是不一样的。有了这个,可以计算出来垂直居中的坐标。但是滑动了滚动条怎么依然垂直居中呢?这个时候就要获取当前窗体距离页面顶部的高度>>>详细阅读


本文标题:Prototype的Class.create函数解析

地址:http://www.17bianji.com/kaifa2/JS/24120.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)