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>

猜你喜欢

转载自www.cnblogs.com/carpenterzoe/p/10197763.html