Function 11: Date.prototype.toJSON
提供了从Date类型转成json的方法。
new Date().toJSON(); // "2010-12-06T16:25:40.040Z"
Function 12: Function.prototype.bind
你会发现这个函数的功能和下面的很相似
var arr1 = ['1', '2', '3'], arr2 = ['4', '5', '6']; // 等同于arr1.push(arr2); Array.prototype.push.apply(arr1, arr2); alert(arr1);
bind和上面的不同之处在于apply是直接执行的,而bind只是绑定函数内部的this,并且将函数返回
var tooltip = { text: 'Click here to . . . ' },
overlay = { text: 'Please enter the number of attendees' };
function showText () {
// really, do something more useful here
alert(this.text);
}
tooltip.show = showText.bind(tooltip);
tooltip.show();
overlay.show = showText.bind(overlay);
overlay.show();
Browser Support
○ Firefox 4
○ Internet Explorer 9
○ Chrome 7+
Function 13: Date.now()
大致这个函数就是等同于new Date().getTime() or +new Date,不是什么大的改动
Function 14: Object.getPrototypeOf
这个函数提供了从通过Object.create得到的对象中提取原型的方法,当然,如果这个对象是通过老的new
function的方法创造出来的,那也可以通过这个方法得到原型
var Dog = {
name : 'dog',
paws : 4,
hungry : false,
speak : function () { return 'Woof!'; }
};
var dog = Object.create(Dog);
// true
alert(Object.getPrototypeOf(dog) === Dog);
// 老方法判断
function Cat() {}
// true
alert(Object.getPrototypeOf(new Cat()) === Cat.prototype);
Function 15: String.prototype.trim
用来去除字符串两边的空格
var origin = " foo "; document.write(origin.trim());
Function 16: Array.prototype.indexOf
这个函数用来返回查找的对象在数组中第一次出现的index
他有两个参数,第一个参数是要查找的对象,第二个参数是查找的起始位置
var array = [2, 5, 9];
var index = array.indexOf(2);
// index is 0
index = array.indexOf(7);
// index is -1
var element = 5;
var indices = [];
var idx = array.indexOf(element);
while (idx != -1) {
indices.push(idx);
idx = array.indexOf(element, idx + 1);
}
当然如果浏览器没有支持indexOf,你可以用以下方法实现
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement /*, fromIndex */) {
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (len === 0)
return -1;
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n !== n)
n = 0;
else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
if (n >= len)
return -1;
var k = n >= 0
? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement)
return k;
}
return -1;
};
}
本文介绍了ECMAScript 5中新增的实用功能,包括Date类型到JSON的转换、Function的bind方法、Date.now()快速获取时间戳、Object.getPrototypeOf用于原型提取、String.trim去除字符串空白、Array.indexOf查找元素位置等。

被折叠的 条评论
为什么被折叠?



