第一种:工厂模式
function work(name, sex) {
//函数里面封装对象 返回对象
var obj = new Object();
//设置相关属性
obj.name = name;
obj.sex = sex;
obj.sleep = function () {
return "正在睡觉!";
}
return obj;
}
var object = work("张三", "男");
console.log(typeof object);
第二种:构造函数模式
function bullet() {
this.width = 20;
this.height = 15;
this.speed = 10;
this.g = 9.8;
this.flymove = function () {
}
}
var b = new bullet();
console.log(b);
第三种:原型模式
原型模式开发,即原型链模式开发会导致不同的对象之间数据共享
function person() {
}
person.prototype.sleep = function () {
return "睡觉";
}
person.prototype.name = "张三";
var p = new person();
console.log(p);
var p1 = new person();
console.log(p1);
构造模式 + 原型链模式:
function f1() {
this.name = "张三"
}
f1.prototype.sleep = function () {
return "打游戏"
}
var f = new f1();
console.log(f);
单例模式:
var obj = (function () {
var newobj;
function getobj() {
//实例化对象 返回对象
if (newobj == undefined) {
newobj = new factory();
}
return newobj;
}
//创建对象的实例
function factory() {
//对象的封装
this.name = "";
this.sex = "";
this.sleep = function () {
}
}
return {
getObj: getobj
}
})();
console.log(obj.getObj());