JavaScript构造函数的方法

134 阅读1分钟

构造函数就是初始化一个实例对象,对象的prototype属性是继承一个实例对象。

方法1

        // 函数
        function Play(){
            // 必须先自己构造一个函数,以后将这个函数名作为对象名
        }
        // 实例化对象
        var p = new Play();
        p.width=300;
        p.height=200;
        p.num=4;
        p.autotime=3;
        // 方法
        p.autoplay=function(){
            alert("play........")
        }
        p.test=function(){}
        alert(p.width);
        p.autoplay();

方法2

        function play(){
            var p = new Object();
            p.width = 300;
            p.height = 200;
            p.num = 4;
            p.autotime = 3;
            p.autoplay = function(){
                alert("play.........")
                alert(this.num)
            }
            p.test = function(){}
            return p;
        }
        var obj = play();
        alert(obj.width);
        obj.autoplay();

方法3

        function play(width,height,num){
            this.width=width;
            this.height=height;
            this.num=num;
            this.autoplay=function(){
                alert("#######");
            }
            this.test-function(){
            }
            return this
        }
        var p = new play(300,200,8);
        alert(p.width);
        p.autoplay();