- 用类实例化对象实现
// 篮球基类
var Basketball = function() {
this.intro = "篮球盛行于美国";
};
Basketball.prototype = {
getMember : function() {
console.log("每个队伍需要5名队员");
},
getBallsize: function() {
console.log("篮球很大");
}
};
// 足球基类
var Football = function() {
this.intro = "足球在世界范围内很流行";
};
Football.prototype = {
getMember : function() {
console.log("每个队伍需要11名队员");
},
getBallsize: function() {
console.log("足球很大");
}
};
// 运动工厂
var SportsFactory = function(name) {
switch(name) {
case 'NBA':
return new Basketball();
case 'wordcup':
return new Football();
}
}
var football = SportsFactory("wordcup");
console.log(football);
console.log(football.intro);
football.getMember();
- 通过创建新的对象并扩展属性和方法来实现
// 工厂模式并
function createBook(name, time, type) {
// 创建一个对象,并对对象扩展属性和方法
var o = new Object();
o.name = name;
o.time = time;
o.type = type;
o.getName = function() {
console.log(this.name);
};
// 将对象返回
return o;
}
var book1 = createBook("js book", 2014, "js");
var book2 = createBook("css book", 2013, "css");
book1.getName();
book2.getName();
我觉得上面
网友评论