品味prototype1.6 新加入方法
来源:互联网 发布:mysql 无需密码登录 编辑:程序博客网 时间:2024/05/01 12:03
prototype在很多模块上加了很好用的方法,本次仅针对Function中一些地方共同品味一下
回味一下bind方法
当初刚接触prototype时最疑惑的地方是Function中bind方法
对于初学者,我教你这样理解
新方法
mootools的还可以绑定一个闭包(对象),而他仅是普通function的延时执行,如果那个function里面如果含有this的话,将得不到引用
先理解、消化了再说
还有curry,wrap方法以后再续
不支持偶的观点望批评指正
回味一下bind方法
当初刚接触prototype时最疑惑的地方是Function中bind方法
CODE:
Function.prototype.bind = function() {
var __method = this;//获得当前方法的引用 (run.bind(this); 就是run)
var args = $A(arguments);
//获得传递给bind方法的参数 并转化为数组
//应用run.bind(this,1,2,3) args就是[(this对象的引用),1,2,3]
var object = args.shift();
//就是把(this对象的引用)提取出来
return function() {
return __method.apply(object, args.concat($A(arguments)));
//这里的arguments又是另外一个了
//比如 var kk = run.bind(this,1,2,3);
// kk(4,5);这里的arguments就是[4,5]
}
}
但这个方法实在很实用对于初学者,我教你这样理解
CODE:
function run(){
if(this.timer){
alert('获得了this对象');
return;
}
this.timer = setTimeout(run.bind(this),1000);
//问题: run你不加bind(this)的话会怎么样
//1秒后由setTimeout调用的这个函数,如果不bind(this)的话 函数中this这个对像会丢失
// 也就永远不会alert('获得了this对象'); 而且进入每隔1秒重复调用run()死循环
// run.bind(this)() = run.apply(this)
}
mootools中也有 不过mootools有点变态(仅个人观点,不代表phpchina观点),多加了个create方法,有点画蛇添足之嫌,代码就不贴了新方法
- 延时执行
CODE:
Function.prototype.delay=function() {
var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
return window.setTimeout(function() {
return __method.apply(__method, args);
}, timeout);
}
上面bind的介绍看懂了的话,这个就很轻松能看懂,不知道他是不是抄袭mootools的 mootools中可是先有这个方法的mootools的还可以绑定一个闭包(对象),而他仅是普通function的延时执行,如果那个function里面如果含有this的话,将得不到引用
CODE:
var obj = function(){
this.kk = '你得到我了';
(function(){
alert(this.kk)// prototype 中会空值
}).delay(1,1,2,3);//延时一秒执行,传递参数1,2,3
}
new obj();
- methodize方法
CODE:
Function.prototype.methodize=function() {
if (this._methodized) return this._methodized;
var __method = this;
return this._methodized = function() {
return __method.apply(null, [this].concat($A(arguments)));
};
}
代码意思是把对象作为参数合并到其参数中,不知道在哪有用途先理解、消化了再说
CODE:
var obj = function(){
var kk = (function(){
alert(arguments[0]);// IE中打印object
alert(arguments[1]);// 这才打印第一个参数
}).methodize();//methodize方法不接受参数
kk('第一个参数',2,3);
}
new obj();
- argumentNames方法
CODE:
Function.prototype.argumentNames=function() {
var names = this.toString().match(/^[/s/(]*function[^(]*/((.*?)/)/)[1].split(",").invoke("strip");
return names.length == 1 && !names[0] ? [] : names;
};
主要是用toString方法获得函数代码,利用正则或得参数列表还有curry,wrap方法以后再续
不支持偶的观点望批评指正
- 品味prototype1.6 新加入方法
- ProtoType1
- 向GridView中加入新行方法
- jdk8新加入的default方法
- 新加入
- 新加入
- 新加入
- 新加入
- 新加入
- 品味
- 品味
- 品味Eclipse 3.1 中的新特性
- ext2.0不能与prototype1.6一起使用
- 新成员加入
- 加入新链接
- 哇~新加入
- 加入新环境
- 加入一个新集体
- oracle自增长字段
- 监听到了CTabItem的关闭事件后,如何不关闭它
- abap编程的一些例子 事件的触发及处理
- 读取硬盘序列号
- install oracle on linux
- 品味prototype1.6 新加入方法
- RSA算法
- log4j介绍和使用方法
- 典型的色彩空间
- JSF内容概述
- 看看 类的序列化及反序列化的耗时
- why can not across external form the inter of a thread
- 2008北京图书订货会——后期报道
- Excel 中用公式统计唯一值的方法