1.单例模式
var singleParten = (function(){
var singgle;
var init = function(){
console.log(66666)
// return {
// }
}
return {
getSingle:function(){
if(!singgle){
singgle = init();
}
return singgle;
}
}
})()
var singgle1 = singleParten.getSingle()
console.log(singgle1)
var singgle2 = singleParten.getSingle()
console.log(singgle2)
console.log(singgle1 === singgle2)
// 实现单体模式弹窗
var createWindow = (function(){
var div;
return function(){
if(!div) {
div = document.createElement("div");
div.innerHTML = "我是弹窗内容";
div.style.display = 'none';
document.body.appendChild(div);
}
return div;
}
})();
document.getElementById("Id").onclick = function(){
// 点击后先创建一个div元素
var win = createWindow();
win.style.display = "block";
}
2.构造函数模式
function constructorParten(name, age){
this.name = name;
this.age = age;
this.say = function(){
return this.name
}
}
var perple = new constructorParten("张三",20)
console.log(perple.say())
3.工厂模式
function factoryParten(opts){
var obj = new Object();
obj.name = opts.name;
obj.adress = opts.adress;
obj.job = function(){
return obj.name
}
return obj;
}
var factory1 = new factoryParten({name:'钢铁厂',adress:'北京市'})
console.log(factory1.job())
4.模块模式(模块模式使用了一个返回对象的匿名函数。在这个匿名函数内部,先定义了私有变量和函数,供内部函数使用,然后将一个对象字面量作为函数的值返回,返回的对象字面量中只包含可以公开的属性和方法。这样的话,可以提供外部使用该方法;由于该返回对象中的公有方法是在匿名函数内部定义的,因此它可以访问内部的私有变量和函数。)
var modelParten = (function(){
var name = "lalala";
var modelsOne = function(){
return this.name;
}
var modelsTwo = function(){
console.log("this is a modelParten demo")
}
return {
modelsOne:modelsOne,
modelsTwo:modelsTwo
}
})()
console.log(modelParten.modelsOne())
console.log(modelParten.modelsTwo())
//图片预加载
var myImage = (function(){
var imgNode = document.createElement("img");
document.body.appendChild(imgNode);
return function(src){
imgNode.src = src;
}
})();
5.代理模式
var ProxyImage = (function(){
var img = new Image();
img.onload = function(){
myImage(this.src);
};
return function(src) {
myImage("http://img.lanrentuku.com/img/allimg/1212/5-121204193Q9-50.gif");
img.src = src;
}
})();
// 调用方式
ProxyImage("https://img.alicdn.com/tps/i4/TB1b_neLXXXXXcoXFXXc8PZ9XXX-130-200.png");
6.组合继承
function Parents(){
this.name = name;
this.age = age;
}
function Child(){
Parents.call(this)
this.name = name;
}
Child.prototype = new Parents();
Child.prototype.constructor = Child;
var child1 = new Child()