面向对象编程

2017-11-22  本文已影响0人  饥人谷_星璇

OOP 指什么?有哪些特性

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

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.sayName = function () {
        console.log(this.name,this.age);
    };
}//对this添加属性和方法
var person1 =  new Person('xiaoming', 18)
var person2 =  new Person('xiaofang', 17)//使用new创造一个新对象,将构造函数的作用域赋给新对象
person1.sayName() //xiaoming 18
person2.sayName() //xiaofang 17 //新构造的函数继承了父类的属性和方法

prototype 是什么?有什么特性

画出如下代码的原型图

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('前端');
IMG_20171116_233253.jpg

(字很丑请勿见怪- -)

创建一个 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('run')
  },
    stop : function(){
    console.log('stop')
  },
    getStatus : function(){
    console.log('getStatus')
  }
}

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

  1. ct属性,GoTop 对应的 DOM 元素的容器
  2. target属性, GoTop 对应的 DOM 元素
  3. bindEvent 方法, 用于绑定事件
  4. createNode 方法, 用于在容器内创建节点
function GoTop(ct){
  this.ct = ct
  this.target = $('<button class="target">GoTop</button>')
  this.bindEvent()
  this.createNode()
}
GoTop.prototype = {
  bindEvent : function(){
    var self = this
    self.target.click(function(){
      $(window).scrollTop(0);
    })
  },
  createNode : function(){
    this.ct.append(this.target)
  }
}//可以用CSS来为targer添加样式或者直接用JQUERY的css API来设置属性
new GoTop($('.ct')) 

demo

使用木桶布局实现一个图片墙

上一篇 下一篇

猜你喜欢

热点阅读