我试图通过增加继承来掌握模块模式。我来自大学背景,我的后备箱中主要使用 Java,但我已经使用 Web 技术大约十年了。不过,我对 JavaScript 的了解只有一年左右......
无论如何,我正在尝试一个简单的继承 ( .prototype
) 示例。从People
对象中,您可以添加Gentleman
',然后使用它们的.toString()
方法列出它们。AGentleman
是 a 的孩子Human
。在我实现“抽象”之前一切顺利Human
,但现在代码将无法运行。
请评论我的代码认为不好的地方。我想继续使用模块/原型方法,但我做错了什么?我也会听听this
不同情况下的含义。即,People
我可以_people
直接使用私有,但在子模块中我必须使用this._name
--why?
var People = People || {};
People = (function() {
var People = function(){
this._people = [];
};
var addGentleman = function (name) {
this._people.push(new People.Gentleman(name));
};
var getList = function () {
var temp = [];
for (var i = 0; i < this._people.length; i++) {
temp.push(this._people[i].toString());
}
return temp;
};
People.prototype.constructor = People;
People.prototype.addGentleman = addGentleman;
People.prototype.getList = getList;
return People;
})();
People.Human = (function () {
var Human = function (name, hasLadyParts) {
this._name = name;
this._hasLadyParts = hasLadyParts;
};
var hasLadyParts = function () {
return this._hasLadyParts;
};
var toString = function () {
var str = this._name;
if (!this._hasLadyParts) str += ' no';
return str + ' lady parts.';
};
Human.prototype.constructor = Human;
Human.prototype.hasLadyParts = hasLadyParts;
Human.prototype.toString = toString;
return Human;
})();
People.Gentleman = (function () {
var Gentleman = function (name) {
People.Human.call(this, name, false);
}
var toString = function () {
return 'Mr.' + People.Human.toString();
};
// Gentleman.prototype = Object.create(People.Human.prototype);
Gentleman.prototype.constructor = Gentleman;
Gentleman.prototype.toString = toString;
return Gentleman;
})();
$(function () {
var people = new People();
people.addGentleman('Viktor');
people.addGentleman('Joakim');
var list = people.getList();
var $ul = $('#people');
for (var i = 0; i < list.length; i++) {
$ul.append('<li>' + list[i] + '</li>');
}
});
小提琴:http: //jsfiddle.net/5CmMd/5/
编辑:我已经更新了代码并稍微摆弄了一下。如果我得到这个工作,我想我理解了大部分的设计。我认为,这个示例也可以作为未来 OOP 程序员访问 JavaScript 领域的简单教程。