对象—— 原型

2017-07-14  本文已影响0人  饥人谷_啦啦啦

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

比如:小明——人——动物——生物——物质....
小明是人的实例。 人是动物的实例,同时他还包含小明这一类。这样一直可以溯本追源。每个类,其实也是对象,直到终点。

面向对象的思想,我觉得应该就是我们在设计程序的时候,由上而下的设计,就是尽可能先创造出物质这个东西,然后再实例化,创造生物,再创造动物,这样,感觉我们再使用的时候,代码就有很大复用性,我们下次再创造小红的时候不要简单太多,只要加新特性就可以了。假如我们一不小心创造了一个邪恶的小红,直接删除她,也不用太伤心,因为再创造一个小红也很轻松。

特性:
1.继承:小明继承人的一些属性和方法。
2.封装:使用小明的人不需要知道小明是怎么跑和跳的,只需要知道小明能跑能跳就行了。
3.多态:想让小明天生是个运动员,我们只需要让小明跑和跳的方式和普通大众不一样就可以了。

原则:开放封闭。
扩展开放:为了增强代码的功能性,你可以随意扩展功能,只要你厉害,完全可以写出更简单的代码实现更多的功能。
修改封闭:但是为了避免你瞎比操作,导致源码丧失基本功能,不能让你瞎比改。

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

function Cat(name){
  this.name=name
  this.sayname=function(){
    console.log('hello,'+this.name)
  }
} 

var cat1=new Cat('miao')
console.log(cat1.name)
console.log(cat1.sayname())

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

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('前端');
自己画的

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

function Car(){
  this.name='auto'
  this.color='blue'
  this.status='run'
  this.run=function(){
    console.log(this.name)
  }
  this.stop=function(){
    console.log('never')
  }
  this.getStatus=function(){
    console.log(this.status)
  }
}

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

function GoTop($ct,$target){
  this.$ct=$ct
  this.taget=$target
  this.bindEvent()
}
GoTop.prototype={
  bindEvent:function(){
    var that=this
    this.creatnode().on('click',function(){
      $(window).scrollTop()=that.target.offset().top
    })
  },
  creatnode:function(){
    var $node=$('<div class=gotop>gotop</div>')
    this.$ct.append($node)
    return $node
  }
}
var go=new GoTop($('.ct'),$('.ct'))

7.代码

http://js.jirengu.com/xokukupihe/1/edit?html,js,output

上一篇 下一篇

猜你喜欢

热点阅读