面向对象和原型

2017-06-10  本文已影响0人  andreaxiang

1. OOP 指什么?有哪些特性?

2. 如何通过构造函数的方式创建一个拥有属性和方法的对象?

function People(name,age){
  this.name=name,
  this.age=age
  this.sayHi = function(){
    console.log("Hi,my name is "+p1.name+" ,I'm "+p1.age+" years old");
  }
}
var p1 = new People("andrea",20);
p1.sayHi();  

3. prototype 是什么?有什么特性?

4. 画出如下代码的原型图

function People (name){
  this.name = name;
  this.sayName = function(){
    console.log('my name is:' + this.name);
  }
}

People.prototype.walk = function(){
  console.log(this.name + ' is walking');  
}

var p1 = new People('大象象');
var p2 = new People('Andrea');
原型

5. 创建一个 Car 对象,拥有属性name、color、status;拥有方法run,stop,getStatus

function Car(name,color,status){
  this.name = name;
  this.color = color;
  this.status = status;
}
Car.prototype.run = function(){
  console.log(this.name+" is runing");
};
Car.prototype.stop = function(){
  console.log("Please stop this "+this.color+" car");
};
Car.prototype.getStatus = function(){
  console.log("This car is level "+this.status);
};
var car1 = new Car("BMW","red","2");
var car2 = new Car("LEXUS","black","1");

car1.run();
car1.stop();
car1.getStatus();

car2.run();
car2.stop();
car2.getStatus();

6. 创建一个 GoTop 对象,当 new 一个 GotTop 对象则会在页面上创建一个回到顶部的元素,点击页面滚动到顶部。拥有以下属性和方法:

  1. ct属性,GoTop 对应的 DOM 元素的容器
  2. target属性, GoTop 对应的 DOM 元素
  3. bindEvent 方法, 用于绑定事件
  4. createNode 方法, 用于在容器内创建节点

html部分

<style>
  li {
    background-color: pink;
    height: 100px;
    list-style: none;
    border:1px solid #fff;
    text-align:center;
    line-height:100px;
  }
</style>
<body>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
    <li>11</li>
    <li>12</li>
    <li>13</li>
    <li>14</li>
    <li>15</li>
    <li>16</li>
    <li>17</li>
    <li>18</li>
    <li>19</li>
    <li>20</li>
  </ul>
</body>

JS 部分

<script src='http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js'></script>
<script>
    function GoTop($ct) {
      this.$ct = $ct;
      this.$target = $('<button class="btn">GoTop</button>');
      this.$target.css({
        position: 'fixed',
        right: '100px',
        bottom: '100px'
      })
    }
    GoTop.prototype.creatNode = function() {
      this.$target.appendTo(this.$ct);
      this.$target.hide()
    }
    GoTop.prototype.bindEvent = function() {
      var _this = this;
      $(window).on('scroll',function() {
        if ($(window).scrollTop() < 100) {
          _this.$target.hide();
        }else {
          _this.$target.show();
        }
      });
      this.$target.on('click',function() {
        $(window).scrollTop(0);
      });
    }
    var GoTop1 = new GoTop($('body'));
    GoTop1.creatNode();
    GoTop1.bindEvent();
</script>

效果预览

上一篇 下一篇

猜你喜欢

热点阅读