1. 工厂模式
缺点:1.没有new 2.浪费内存
function createPerson(name,age){
//原料
var obj = new Object();
//加工
obj.name = name;
obj.age = age;
obj.say = function(){
console.log("我叫:"+this.name)
}
//出厂
return obj;
}
调用方法:
var person = createPerson("zhangsan",18)
person.say()
2. 构造函数
function createPerson(name,age){
//系统帮我们创建了this
// var this = new Object()
this.name = name;
this.age = age;
this.say = function(){
console.log("我叫:"+this.name)
}
}
// 系统帮我们把this返回
// return this
//p 和 p2 叫实例, 构造函数的this指向的是实例
var p = new CreatePerson("zhangsan",15)
console.log(p)
3. 原型
CreatePerson.prototype={
legs:2,
say:function(){
console.log("我叫:" + this.name)
}
}
4. 构造函数 + 原型
将自己的属性和方法放到构造函数中,
将共用的属性和方法放到原型上
function CreatePerson(name, age) {
this.name = name
// this.legs = 3
}
CreatePerson.prototype={
legs:2,
say:function(){
console.log("我叫:" + this.name)
}
}
下面举一个实例来应用一下面向对象的知识:
下面是一个拖拽实例,一个正方形可以随意的被拖拽,另外一个正方形则不能超出页面可视区的位置。
HTML部分
<div id="box1"></div>
<div id="box2"></div>
CSS部分
<style>
div {
width: 100px;
height: 100px;
background-color: #000;
position: absolute;
top: 0;
left: 0;
}
#box2 {
background-color: red;
}
</style>
JS部分
<script src="../jquery-1.12.4.js"></script>
<script>
$(function () {
function Drag(id) {
this.$box = $("#" + id)
var _this = this
this.$box.mousedown(function () {
_this.move()
_this.up()
})
}
Drag.prototype = {
move: function () {
// console.log(this)
var _this = this
$(document).mousemove(function (e) {
// console.log(this) //document
var left = e.clientX - 50,
top = e.clientY - 50
_this.$box.css({
top: top,
left: left
})
})
},
up: function () {
$(document).mouseup(function () {
$(document).off("mousemove mouseup")
})
}
}
function Drag2(id) {
Drag.call(this, id)
}
Drag2.prototype = extend(Drag.prototype)
Drag2.prototype.move = function () {
var _this = this
$(document).mousemove(function (e) {
// console.log(this) //document
var left = e.clientX - 50,
top = e.clientY - 50
if(left<=0){
left = 0
}
_this.$box.css({
top: top,
left: left
})
})
}
/**
*@method extend 对象的浅复制
*@param{object} obj 要拷贝的对象
*@return {object} 复制完成的对象
*/
function extend(obj) {
var obj2 = {}
for (var key in obj) {
obj2[key] = obj[key]
}
return obj2;
}
new Drag("box1")
new Drag2("box2")
})
</script>
效果图如图所示:
总结:
普通函数和构造函数的区别有以下几点:
- 构造函数就是普通函数
- 构造函数中声明变量不再用var,而是用this
- 为了区别普通函数和构造函数,构造函数的函数名首字母大写
- 构造函数在使用的时候需要使用 new
- 构造函数中,this指向的是当前对象