构造函数js

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript">
        function People(name,age){
            this.name=name;
            this.age=age;
            this.fn=function(){
                alert(this.name+","+this.age);
            };
            //return 1; 如果返回是非对象,实例化时就隐式的返回一个对象;若返回的是一个对象[对象,数组,函数],实例化的对象就是这个对象
            /*return {
                a:1
            };*/
            /*return function(){
                var a=0;
                alert(2);
            };*/
            /*return [2,3,32];*/
            //return "21";
        }
        //People.prototype=
        var p1=new People("sun",22);
        var p2=new People("QQ",12);
        p1.fn();
        p2.fn();
        //console.log(p1.fn==p2.fn);//false, 每个实例都有一个函数,浪费空间

        function Car(color,age){
            this.color=color;
            this.age=age;
        }
        Car.prototype.showColor=function(){
             alert(this.color);
        }; //如果是个对象,若有个实例改变了,其它也改变了;
        Car.prototype.hello=new function(a){
            this.a=a;
        };
        Car.prototype.showAge=function(){
            alert(this.age);
        };
        var c1=new Car("red",1);
        var c2=new Car("green",2);
        c1.showColor();
        c2.showAge();
        c1.hello(2);
        alert(c2.hello().a); //弹出来的是2

        console.log(c1.showColor==c2.showColor);//true, 每个实例指向同一个函数;
    </script>
</head>
<body>

</body>
</html>

 

posted @ 2014-03-14 10:30  叶知秋红  阅读(211)  评论(0编辑  收藏  举报