我正在尝试学习如何在Javascript&中创建类。如何执行对象继承。我已经按照一些教程,但我不确定我的代码是否正确。
这是我创建基类然后是子类的简单代码:
/* 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?
}
}
答案 0 :(得分:2)
How to Achieve Private, Public, Privileged members in Javascript
虽然我不建议你写这样的代码。 JavaScript与C ++不同。不要用JavaScript编写C ++代码。
答案 1 :(得分:0)
在JS中认真继承并不是那么有用。如果您需要将函数复制到另一个对象,只需在该对象的上下文中调用它们即可。我在Java领域做了大量的OOP,但是通过使用上下文和回调可以很容易地避免javascript中的继承。也就是说,如果您认为需要继承层次结构,则可能只需要回调或在不同的上下文中调用该函数。
但要回答不是“正确”方式的问题,请查看javascript g arden
function Foo() {
this.value = 42;
}
Foo.prototype = {
method: function() {}
};
function Bar() {}
// Set Bar's prototype to a new instance of Foo
Bar.prototype = new Foo();
Bar.prototype.foo = 'Hello World';
// Make sure to list Bar as the actual constructor
Bar.prototype.constructor = Bar;
var test = new Bar() // create a new bar instance