|Genre:||Health and Food|
|Published (Last):||13 February 2006|
|PDF File Size:||12.34 Mb|
|ePub File Size:||5.47 Mb|
|Price:||Free* [*Free Regsitration Required]|
A better approach would be to store the characters and the corresponding bug-constructors in a dictionary, and look for them there:.
Like a real wall, it doesn’t do much, it just sits there and takes up space. We can make a simple, stupid bug that always just goes south, ‘towards the light’, like this: Fortunately, all we have to do is to make the elementFromCharacter function more general.
Instead of providing regular functions for working with the objects, they provide a way to create such objects, using the new keyword, and a number of methods and properties that provide the rest of the interface. Multiple inheritance, though extremely useful in some situations, can be safely ignored most of the time. Using this, we could rewrite our properties method like this:. We will take a rather simple approach, and make the terrarium a two-dimensional grid, like the second map in chapter 7.
This way, objects of the new type can be polymorphically used in all the places where objects of the old type could be used.
It should only be called on constructors whose prototype does actually have a character property. SmallItem can be seen as such a prototype.
It has four methods: Unless someone actually messes with the method in Object. By always picking a random direction, it will often move back and forth without getting anywhere. Thus, any this variable outside of the function will not be visible. This is easy to do, and in some cases it is the best solution, but in this case there is a cleaner way. A related problem is that it can often be practical to extend the prototypes of standard constructors such as Object and Array with new useful functions.
Thus, the question of whether inheritance is being used correctly boils down to the question of whether the resulting code works correctly and avoids useless repetitions. Note that the values property of a Dictionary object is not part of this interface, it is an internal detail, and when you are using Dictionary objects you do not need to directly use it. This method has to go over all the bugs on the grid, ask them for an action, and execute the given action. Add a method toString to the Terrarium prototype, which takes no arguments and returns a string that, when given to printshows a nice two-dimensional view of the terrarium.
Objects play both the role of ‘values with methods’, for which prototypes work great, and ‘sets of properties’, for which prototypes only get in the way.
Note that the action function is called with both the name of the property and the value it has in the object. This will make it easier to write the toString function of the terrarium later.
Each property holds a string of one character, as javasript.programowanie by characterFromElementindicating what the bug can see in that direction.