Sea.JS
Seajs結合javascript物件導向
所需頁面
/app/index.html
/lib/factory.js
/lib/sea.js
/lib/constructor.js
/js/init.js
程式碼
Index.html
<!DOCTYPE html>
<html>
<head>
<title>物件導向</title>
<meta charset="utf-8" />
</head>
<script src="../lib/sea.js"></script>
<body>
<script type="text/javascript">
seajs.use("../js/init.js");
</script>
</body>
</html>
Factory.js
define(function(require,exports){
//工廠方式
function createObject(name,age) {
var o = new Object();
o.name = name;
o.age = age;
o.say = function() {
alert(this.name+"-"+this.age);}
return o;
}
exports.createObject=createObject;
});
Constructor.js
define(function(require,exports){
//建構函式方式
function Person_constructor(name,age) {
this.name = name;
this.age = age;
this.say=function(){
alert(this.name+"="+this.age);
}
}
exports.Person = Person_constructor;
});
Init.js
//init.js
define(function(require, exports, module) {
var factory = require('../lib/factory') ;
var constructor = require('../lib/constructor');
//工廠方式建立物件
var b = factory.createObject("ajck",11);
//建構函式方式
var b2 = new constructor.Person("leno",22);
//解決工廠方式不能使用instanceof判斷物件,因為工廠方式建立instanceof 是Object
console.info(b2 instanceof constructor.Person);
b2.say();});