搞不懂得js,说明白了分全给了,越明白越好
在js的基础上封装的,common.js如下
var Tecent = Tecent || {};
Tecent.Common = Tecent.Common || ((function() {
var Common = {
extend: function(base, obj) {
for (var i in base) {
obj[i] = base[i];
}
return obj;
},
Inheritance: function(base, obj) {
for (var i in base.prototype) {
obj.prototype[i] = base.prototype[i];
}
return obj;
}
}
Common.extend({
Trim: function() {
return this.replace(/^\s+/, '').replace(/\s+$/, '');
}
}, String.prototype);
window.Co = Common;
return Common;
})());
使用方法
Forms.Panel = Forms.Panel || ((function() {
var Panel = function(n, i) {
this.Init(n, i);
}
Tecent.Common.Inheritance(Forms.Base, Panel);//为什么要先这样继承,再接下来extend呢?
Co.extend({
Controls: null,
Init: function(n, i) {
this.Controls = [];
if (i == undefined) {
i = n;
this.Element = $('<span></span>');
}
else {
this.Element = $(n);
}
if (i) {
this.Show()
}
else {
this.Hide();
}
},
//添加一个控件到容器
Add: function(obj) {
if (obj.Element) {
this.Element.append(obj.Element);
this.Controls.push(obj);
}
else {
this.Element.append($(obj));
}
return this;
},
//删除容器//或容器内控件
Remove: M(function() {
this.Element.remove();
this.Controls = [];
}, function(obj) {
if (obj.Element) {
obj.Element.remove();
this.Controls.RemoveKey(obj);
}
else {
$(obj).remove();
}
})
}, Panel.prototype);
return Panel;
})());
1 为什么扩展和继承要这么写,可以这么写?而不是平时看书上说的,用call,或者apply去实现继承呢?extend是重写了jquery的方法吗?
extend: function(base, obj) {
for (var i in base) {
obj[i] = base[i];
}
return obj;
},
Inheritance: function(base, obj) {
for (var i in base.prototype) {
obj.prototype[i] = base.prototype[i];
}
return obj;
}
他们做了什么工作?为什么要这么做?
2 为什么panel的使用可以
var panel=new Forms.Panel()呢?
而var xyz = xyz || {};
xyz = xyz || (function() {
var refn = function(paramx,paramy) {
return paramx + paramy;
}
return refn;
} ());
debugger;
var thisxyz = new xyz();
这样却是错误的?其实这里错误我明白了,但刚才的panel明明定义后已经执行了,为什么还可以var panel=new Forms.Panel()呢?