0
我想知道如果下面的代碼放在一起是定義用於在js中創建類的包裝函數的最佳方式。Javascript OOP框架
有沒有人有更好的例子願意分享,因爲我認爲這是第一次嘗試。
如果有什麼我錯過了什麼?
j = {
context : {}
};
j.namepsace = (function(){
var createnamespace = function(parent, remainder){
if(remainder.length === 0){
return;
}
parent[remainder[0]] = parent[remainder[0]] || {};
return createnamespace(parent[remainder[0]], remainder.splice(1));
};
return {
define : function(ns){
createnamespace(j.context, ns.split('.'));
}
}
}());
j.class = (function(){
return {
construct : function(namespace, name, ctor){
namespace[name] = ctor;
},
ctor : function(namespace, name, ctor, prototype){
for (var property in prototype) {
if (prototype.hasOwnProperty(property)) {
ctor.prototype[property] = prototype[property];
}
}
namespace[name] = ctor;
}
}
}());
j.mixin = (function(){
return {
with : function(object, objectliteral){
for (var prototype in objectliteral) {
if (objectliteral.hasOwnProperty(prototype)) {
object[prototype] = objectliteral[prototype];
}
}
},
toDefintion : function(classdefinition, mixin){
var objectliteral = mixin();
for (var property in objectliteral) {
if (objectliteral.hasOwnProperty(property)) {
classdefinition.prototype[property] = objectliteral[property];
}
}
}
};
}());
j.namepsace.define('application.section');
j.class.construct(j.context.application.section,'printNameMixin', function(){
return {
printName : function(){
console.log(this.name);
}
};
});
j.class.construct(j.context.application.section,'person',function(name, address, age){
return {
name : name,
address : address,
age : age
};
});
j.class.ctor(j.context.application.section,'customer',function(name){
this.name = name;
}, {
name : 'unregistered client'
});
j.mixin.toDefintion(j.context.application.section.customer, j.context.application.section.printNameMixin);
var person = j.context.application.section.person('Blair Davidson','23 Test St',33);
var cust = new j.context.application.section.customer("Bankwest");
cust.printName();
console.log(person);
位開放式是這個... – 2014-10-08 08:34:56
看起來像它導致了很多點,但如果它起作用,它至少是好的。 – dandavis 2014-10-08 09:17:14