高级1:对象 & 原型

2018-09-21  本文已影响0人  饥人谷_哈噜噜

问题1: OOP 指什么?有哪些特性

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

function Person(name,age){
    this.name = name;
    this.age = age;
    this.printName = function(){
        console.log(this.name)
    }
}

var p1 = new  Person('haha', 18)

问题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('前端');

原型图.jpg

问题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 running')
    },
    stop : function(){
        console.log(this.name + 'is stop')
    },
    getStatus : function(){
        console.log(this.name + 'is getStatus')
    }
}

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

要求:

1. `ct`属性,GoTop 对应的 DOM 元素的容器
2. `target`属性, GoTop 对应的 DOM 元素
3. `bindEvent` 方法, 用于绑定事件
4. `createNode` 方法, 用于在容器内创建节点
html+css部分:
<!DOCTYPE html>
<html>
<head>
  <script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
  <meta charset="utf-8">
  <title>对象原型实践</title>
  <style>
      #ct{
         min-width: 800px;
         height: 3000px;
         border: 1px solid #ccc;
      }
      .go-top{
          width: 100px; 
          height: 25px;
          line-height: 25px;
          border: 1px solid #333;
          border-radius: 3px;
          text-align: center;
          position: fixed; 
          right: 30px; 
          bottom: 30px; 
          cursor: pointer; 
      }
      .hide{
          display: none;
      }
  </style>
</head>
<body>
  <div id="ct">
    <div class="go-top hide"></div>
  </div>
</body>
</html>
js部分:
var GoTop = function(ct, target){
  this.ct = ct;
  this.target = target;
  this.bindEvent();
  this.target.html(this.createNode());
}
GoTop.prototype = {
  bindEvent: function(){
    var _this = this;
    $(window).on('scroll',function(){
      if($(window).scrollTop()>200){
        _this.target.removeClass('hide');
      }else{
        _this.target.addClass('hide');
      }
    })
    _this.target.on('click',function(){
      $(window).scrollTop(0)
    })
  },
  createNode: function(){
    return '<span>回到顶部</span>'
  }
}
var $ct = $('#ct')
var $goTop = $('.go-top')
new GoTop($ct,$goTop)

问题7: 使用木桶布局实现一个图片墙

上一篇 下一篇

猜你喜欢

热点阅读