面向对象,函数构造方法代码举例

<!DOCTYPE html>  
<html>   
    <head>  
        <meta charset="UTF-8">  
        <title>面向对象,函数构造方法1</title>  
    </head>   
    <body>  
    </body>  
    <script>  
    /*(function(){}());将变量方法等搞成不同作用域,即封装某些代码块,后加()是为了可以执行*/  
    (function(){  
        var n="局部作用域的变量n";  
        function people(name,age,sex){//people类的构造函数  
            this.name=name;  
            this.age=age;  
            this.sex=sex;  
        }  
        people.prototype.n=n;  
        people.prototype.say=function(){  
            alert("people----say");  
        }  
        window.people=people;//赋值给window,全局才可以调用           
    }());     
    (function(){  
        function stu(name,age,sex){//stu类的构造函数  
            this.name=name;  
            this.age=age;  
            this.sex=sex;  
        }  
        stu.prototype=new people();//继承people类      
        var speple_say=stu.prototype.say;  
        people.prototype.say=function(){  
            speple_say.call(this);//子类调用父类的say()  
            alert("stu----say");//重写父类say()  
        }  
        window.stu=stu;//赋值给window,全局才可以调用  
    }());    
    var p=new people('小明','12','男');  
    p.say();  
    alert(p.name+"  "+p.n);  
    var s=new stu();  
    s.say();  
    alert(s.n);  
    </script>  
</html>
<!DOCTYPE html>  
<html>  
    <head>  
        <meta charset="UTF-8">  
        <title>面向对象,函数构造方法2</title>  
    </head>  
    <body>  
    </body>  
    <script>  
    /*(function(){}());将变量方法等搞成不同作用域,后加()是为了可以执行*/  
    (function(){  
        var n="局部变量n";  
        function people(name){  
            var _this={};//声明_this变量是一个空对象  
            _this.name=name;  
            _this.say=function(){  
                alert("people----say---"+_this.name);  
            }  
            return _this;//个人觉得people更像是一个方法而不是类  
        }  
        window.people=people;  
    }());     
    function stu(name){  
        var _this=people(name);  
        var supersay=_this.say;  
        _this.say=function(){  
            supersay.call(_this);  
            alert("stu----say---"+_this.name);  
        }  
        return _this;  
    }    
    var s=stu('jick');  
    s.say();     
    </script>  
</html>

欢迎分享本文,转载请保留出处:前端ABC » 面向对象,函数构造方法代码举例

分享到:更多 ()

发表评论 0