ECMAScript 5の新しい特性(三)


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を返すために使用されます.
彼は2つのパラメータを持っています.最初のパラメータは検索するオブジェクトで、2番目のパラメータは検索の開始位置です.
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;
      };
}