閱讀599 返回首頁    go 阿裏雲 go 技術社區[雲棲]


javascript 修改對象

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
    <title>修改對象</title>
</head>
<body>
    1.創建新方法:可以用prototype屬性為任何已有的類定義新方法,就像處理自己的類一樣(類似C#裏的擴展方法)。<br />
    <script type="text/javascript">
        //實例1:數字按十六進製輸出
        Number.prototype.toHexString = function () {
            return this.toString(16);
        }
        //調用
        var num = 15;
        alert("實例1:數字按十六進製輸出:" + num.toHexString());
 
        //實例2:數組索引
        Array.prototype.indexOf = function (item) {
            for (var i = 0; i < this.length; i++) {
                if (item == this[i]) {
                    return i;
                }
            }
        }
        //調用
        var colorArr = new Array("red""green""yellow");
        alert("實例2:數組索引:" + colorArr.indexOf("green"));
 
        //實例3:擴展Object類方法
        Object.prototype.showValue = function () {
            return this.valueOf();
        }
        //調用
        var colors = new Array("red""green""yellow");
        var str = "hello";
        alert("實例3:擴展Object類方法:" + str.showValue());
        alert("實例3:擴展Object類方法:" + colors.showValue());
    </script>
</body>
</html>

最後更新:2017-04-03 18:51:44

  上一篇:go javascript 對象繼承
  下一篇:go 雙色點陣