javascript-声明对象及其属性和方法

/*
    方法一
*/
    var p = new Object();    //声明对象
    //为对象添加属性
    p.width=300;
    p.height=400;
    p.num=4;
    p.autotime=3;
    //为对象添加方法
    p.autoplay=function(){
        alert("方法一");
    }
    p.test=function(){
    
    }
    //获取属性对象
    alert("方法一:"+p.width)
    //执行对象方法
    p.autoplay();
  
/*
    方法二
*/
    function Play(){
        var p = new Object();
        //属性
        p.width=300;
        p.height=400;
        p.num=4;
        p.autotime=3;
        //方法
        p.autoplay=function(){
            alert("方法二");
        }
        p.test=function(){
            
        }
        
        return p;
    }

     var p1 = Play();//实例对象
     alert("方法二:"+p1.width);//获取属性值
     p1.autoplay();    //执行方法
     //后期仍然可以往对象里面添加属性方法
     p1.demo = "hello";
/*
    方法三
*/
    function Play1(width,height,num){
        this.width=width;
        this.height=height;
        this.num=num;
        this.autoplay=function(){
            alert("方法三");
        }
        this.test=function(){
            
        }
    }
    var p2 = new Play1(33,44,2);//实例化对象
    alert("方法三:"+p2.width);
    p2.autoplay();

源码下载:http://pan.baidu.com/s/1kTFleKZ

原文地址:https://www.cnblogs.com/next-open/p/3684121.html