我正在尝试学习如何在 Javascript 中创建类以及如何执行对象继承。我已经遵循了一些教程,但我不确定我的代码是否正确。
- 我是否正确创建了公共(public)函数和属性?如果不是,我应该改变什么?
- 我是否正确创建了特权函数和属性?如果不是,我应该改变什么?
- 我是否正确创建了私有(private)函数和属性?如果不是,我应该改变什么?
- 我是否正确地重写了函数?
- 我是否正确执行继承?
- 如果有什么问题,你能告诉我代码应该是什么样子吗?
这是我创建基类然后创建子类的简单代码:
/* Base Object Class */
function BaseClass( /*string*/ objType )
{
/* Public: */
this.name = "blah";
BaseClass.prototype.getName = function()
{
return this.name;
}
BaseClass.prototype.setName = function( newName )
{
var oldName = this.name;
this.name = newName;
return oldName;
}
/* Private: */
var attributeMap = {};
this.constructor = function()
{
// this objects default constructor. Is this correct?
attributeMap["type"] = objType;
attributeMap["uniqueID"] = "Base"+(++INSTANCE_COUNT);
}
/* Privileged: */
// Will an object that inherits from this class be able to override the following functions?
// Or do I have to make these functions public in order to override them?
this.toString = function()
{
var s = "";
for (var attrib in attributeMap)
{
s += attrib + ": " + attributeMap[attrib] + ", ";
}
return s;
}
this.getType = function()
{
return attributeMap["type"];
}
this.renderObject = function()
{
// TODO: render object on HTML5 canvas
}
this.parseXMLNode = function( /*XML Node*/ nodeXML, /*string*/ objType )
{
var attribs = nodeXML.attributes;
for (var i=0; i<attribs.length; i++)
{
attributeMap[ attribs[i].nodeName ] = attribs[i].nodeValue;
}
// store children
if ( nodeXML.hasChildNodes() )
{
attributeMap["children"] = nodeXML.childNodes;
}
reformatObjectInnerHTML();
}
}
// Static Variables //
BaseObject.INSTANCE_COUNT = 0;
// My Child Class //
ChildClass.prototype = new BaseObject( objType ); // make ChildClass inherit from BaseClass
ChildClass.prototype.constructor = function(ObjType) // Make the ChildClass call the BaseClass constructor
{
BaseObject.prototype.constructor.call(this, objType);
}
function ChildClass( /*string*/ objType )
{
/* Privileged: */
// Attempt to override BaseClass function renderObject()
this.renderObject = function()
{
alert("ChildClass::renderObject();");
// Does this override the BaseClass renderObject() function?
}
}
最佳答案
How to Achieve Private, Public, Privileged members in Javascript
尽管我不建议您编写这样的代码。 JavaScript 与 C++ 不同。不要在 JavaScript 中编写 C++ 代码。
关于javascript - Javascript对象和继承的首次尝试: is it correct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8016877/