HTML中构造函数的批量生产

2016-03-18  本文已影响81人  Alexander

前言

本章主要介绍的是JS中构造函数是怎么使用的.

////           创建一个student函数
            function student(){
              console.log('我真的是够了,忘记吃中午饭了');
           }
//            函数的调用
           student();
//           构造函数,批量生产函数
            var student1 = new student();
//          使用new可以快速创建函数,相当于OC中的[[student alloc] init]
          console.log(typeof student1); // object

<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="UTF-8">
        <title>如何批产对象</title>
    </head>
    <body>
        <script type="text/javascript">

            // 构造函数, 没有参数的时候
            var Dog = function(){
               this.name = null;
                this.age = null;
                this.height = null;
                this.run = function(){
                    console.log(this.name + '一直在雨中奔跑,风一样的狗');
                };
                this.eat = function(meat){
                    console.log(this.name + '尼莫,只知道吃肉');
                }
            }

            //            批量生产对象
            var dog1 = new Dog();
            dog1.name = '大黄';
            dog1.age = 1;
            dog1.height = 1.80;
            dog1.width = 150;
            dog1.eat('吃屎吧你');
            dog1.run();

            var dog2 = new Dog();
            dog2.name = '大阿辉';
            dog2.age = 2;
            dog2.width = 70;
            dog2.eat('五花肉');
            dog2.run();

            console.log(dog1, dog2);


        </script>
    </body>
</html>
<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="UTF-8">
        <title>如何批产对象</title>
    </head>
    <body>
        <script type="text/javascript">
<!--有参数的时候-->
          var dog = function(name, age, width){
              this.name = name;
              this.age = age;
              this.width = width;
              this.run = function(){
                  console.log(this.name + '雨中奔跑');
              };
              this.eat = function(meat){
                  console.log(this.name + meat);
              }
          }

//  批量生产构造函数
            var dog1 = new dog('大黄', 1, 150);
            var dog2 = new dog('大灰', 2, 100);
            dog1.run();
            dog2.eat('只会吃屎');
            console.log(dog1.name,dog1.width,dog1.age);
            console.log(dog2.name,dog2.width,dog2.age);

        </script>
    </body>
</html>
有参数.png
上一篇 下一篇

猜你喜欢

热点阅读