- 用類實例化對象實現(xiàn)
// 籃球基類
var Basketball = function() {
this.intro = "籃球盛行于美國";
};
Basketball.prototype = {
getMember : function() {
console.log("每個隊伍需要5名隊員");
},
getBallsize: function() {
console.log("籃球很大");
}
};
// 足球基類
var Football = function() {
this.intro = "足球在世界范圍內(nèi)很流行";
};
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();
- 通過創(chuàng)建新的對象并擴展屬性和方法來實現(xiàn)
// 工廠模式并
function createBook(name, time, type) {
// 創(chuàng)建一個對象,并對對象擴展屬性和方法
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();
我覺得上面