1. 程式人生 > >JS學習筆記 - 面向物件 - 原型

JS學習筆記 - 面向物件 - 原型

 

 

<script>
    var arr1 = new Array(12, 55, 34, 78, 676);
    var arr2 = new Array(12, 33, 1)

Array.prototype.sum = function()  //理解為CSS的Class樣式
//    arr1.sum = function(){      //理解為行間樣式
{
        var result = 0;
    
        for(var i=0; i<this.length; i++)
        {
            result 
+= this[i]; } return result; } alert(arr1.sum()); alert(arr2.sum()); </script>

 

<script>
    function CreatePerson(name, qq)     //建構函式
    {
        //系統偷偷替咱們做:
        // var this = new Object();
    
        this.name = name;
        this.qq = qq;

        
//也會偷偷做一些: // return this; } CreatePerson.prototype.showName = function() //原型 { alert('我的名字叫:' + this.name); }; CreatePerson.prototype.showQQ = function() { alert('我的名字叫:' + this.qq); }; var obj=new createPerson('blue', '258248832'); var obj2
=new createPerson('張三', '45648979879'); /*obj.showName(); obj.showQQ(); obj2.showName(); obj2.showQQ();*/ alert(obj.showName==obj2.showName); </script>