2

I'm learning javascript.

I see that with an object, I can use .prototype, is it fair to say that, in a class/tree hierarchy I am effectively using the 'parent' (or 'ancestor' perhaps) by doing that? Can a class only have 1 prototype at a time as in Ruby?

Call it Personal Homework that I set myself.

1 Answer 1

3

Yes, the prototype property on a given object refers to the parent object, which allows the given object to inherit all its properties and methods. However, the definition of parent probably should be defined here. In a prototype-based language, that means that a single object can be the parent of many other objects. A side effect of this is that a property that changes in the parent is reflected in all child objects, assuming the child objects don't override it. This essentially forms a tree structure of objects that you can traverse. This is different then in a class-based language where the parent refers to the super class, and does not represent a tree of objects. The object also inherits the properties and methods from the parent, but it is all self contained within that one object.

5
  • In some class-based languages (such as Java), classes can have static attributes, which are essentially attached to the class object and only indirectly to the child object. Mar 23, 2012 at 18:38
  • That's good to know Matthew - if they are attached indirectly, how do you access them? Is there a special notation? Do you have to use super or something? Mar 23, 2012 at 18:41
  • 1
    @MichaelDurrant: In Java, static fields and methods are accessible by the class name. (You can access them from object instances, but that is generally discouraged because nothing about the object instance is relevant in a static context.) So if there was a class Foo, then you could call the static method bar by saying: Foo.bar(). Static fields and methods are inherited, but cannot be overidden.
    – Jeremy
    Mar 23, 2012 at 18:44
  • The prototype property does not inherit. The [[Prototype]] is the parent of any object and determines what is inherited
    – Raynos
    Mar 24, 2012 at 19:27
  • @Raynos That's what I meant. Sorry.
    – Jeremy
    Mar 24, 2012 at 22:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.