Which one subsumes the other: class-based object-orientation of prototypal
inheritance?
In this talk: http://www.youtube.com/watch?v=hQVTIJBZook, Douglas
Crockford claims that class-based object-orientation can be represented in
terms of prototypal inheritance. The construction he gives is something
like:
var theObject = function() {
var private1 = ...;
var private2 = ...;
...
return {
public1: ...,
public2: ...,
...
};
};
He also claims that the converse is not true: prototypal inheritance
cannot be in general encoded using class-based constructs only. I have
been thinking about it for a while, and it seems to me that both claims
are wrong.
The supposed "encoding" of class-based object-orientation is wrong from an
operational semantics point of view. In a typical class-based
object-oriented language, member variables and functions are known to
exist, so they can be directly used. The prototypal "encoding" relies on
testing at runtime whether a member with a specific member is present in
an object/hashtable. Ergo, the semantics are different.
Prototypal inheritance actually can be encoded in a class-based
object-oriented language.
I will use C++ as an example, but any other class-based object-oriented
language could be used.
struct prototypal
{
std::shared_ptr<prototypal> base;
std::unordered_map<std::string, boost::any> members;
const member & operator [] (const std::string & key) const
{
auto it = members.find (key);
if (it == members.end ())
{
if (base)
return base [key];
else
throw std::logic_error { "Member not found." };
}
else
return *it;
}
member & operator [] (const std::string & key)
{
auto it = members.find (key);
if (it == members.end ())
{
if (base)
return base [key];
else
throw std::logic_error { "Member not found." };
}
else
return *it;
}
};
Is my analysis wrong? Am I missing something?
No comments:
Post a Comment