8

I know Javascript for some time, although I am not a heavy user, I know it the first from the time when Netscape was my browser. I pretty much understand the main things, but since JavaScript approach to OOP is prototypical I have some problem grasping it.

One problem to add to this it seems that things can be done in more than one way, and here is where books don't help much because they put all the examples on the table making it hard to keep the pace.

What I need for start is only one way of doing it, if someone can help me with the simplest code possible an example where I can see how the prototypal OOP model works?

To be helpful the code should have an inherited object, to access a parent's property and its inherited properties and a parent's function, to overwrite a parent's function and and have an instance of a multiple inheritance where an object inherits two other objects.

Eduard Florinescu
  • 973
  • 2
  • 12
  • 32
  • Hello and a slightly belated Welcome to Programmers. Unfortunately this question is explicitly 5 questions and a number of other implicit questions. This renders it very unfocused and it will likely be closed. If you can focus your question, that might make it more acceptable to the site guidelines. Have a pleasant day. –  Aug 17 '12 at 22:28
  • @WorldEngineer I guess in other language most of the answers to the 5 punctual question can be given in one or few lines. Unfortunately I cannot separate all 5 question and ask them one by one, or can I ? Is this allowed ? – Eduard Florinescu Aug 17 '12 at 22:32
  • 1
    Please ask one question at a time and if you then have further questions ask them as separate but linked questions. – ChrisF Aug 17 '12 at 22:44
  • In the case that your question gets closed, you can search IRC for someplace to talk about javascript, and then use jsfiddle to work with examples. I am sure someone would help you. I don't know enough to accurately answer those questions. I am still learning too ;) – lwm Aug 17 '12 at 22:44
  • 1
    @WorldEngineer I edited the question to be only one – Eduard Florinescu Aug 17 '12 at 22:46
  • @ChirsF Edited the question, should be ok – Eduard Florinescu Aug 17 '12 at 22:47
  • @EduardFloreniscu: I did answer the original version. – Aadaam Aug 17 '12 at 22:54
  • @WorldEngineer the original question was perfectly answerable. – Aadaam Aug 17 '12 at 22:54
  • @Aadaam it's not a question of "could it be answered", it's a question of was it focused on one thing or not? Not several related things, one thing. It's one of the cornerstones of the Stack Exchange model. –  Aug 17 '12 at 22:58
  • @Aadaam And pretty clear too, although I will have to delete it if I will get too many negative votes it was very useful to me, still in console :)! – Eduard Florinescu Aug 17 '12 at 22:59
  • @World Engineer now its concentrated on one thing a code sample that would show the main traits of OOP from a prototypal approach. – Eduard Florinescu Aug 17 '12 at 23:02
  • @WorldEngineer - the question was about prototypical inheritance, of course, everyone has their own expectations on how inheritance works. My personal opinion is that classes are needed, have deep roots in human psychology and prototype is a wrong way, but if I had 2 cents for every dev who doesn't understand prototypical I'd be a millionare, so it's worth answering it again and again. – Aadaam Aug 18 '12 at 01:06
  • 1
    BTW, one thing classical inheritance got wrong is to totally separate methods and properties, on a Neumann-architecture machine (ARM, PowerPC, Intel), it's meaningless. This is something that JS does well. And these were very good questions to illustrate how proto-oop works. – Aadaam Aug 18 '12 at 01:11

3 Answers3

6

How can be inherited an object?

function inherit(o){ // inherit is called Object.create in modern implementations
    var F= function(){};
    F.prototype=o;
    return new F();
}

var parent = {
    name: "Josh",
    print: function(){
       console.log("Hello, "+this.name);
    }
};
parent.print(); // Hello, Josh
var child = inherit(parent);
child.name = "Jeremy";
parent.print(); //Hello, Josh
child.print();  //Hello, Jeremy

How can I see a parent's property?

console.log(child.__proto__.name); //won't work in IE; also see getPrototypeOf

How can I access a parent's function?

Object.getPrototyepeOf(child).print(); // or
child.print.apply(parent) //functions are just objects, and 'this' pointer can point to wherever you want

How can I overwrite a parent's function?

child.print = function(){
    console.log("Hi ", this.name);
}

parent.print(); //Hello, Josh
child.print();  //Hi, Jeremy

How an object can inherit two objects?

//in chain?

grandchild = inherit(child);

//otherwise, there's no way.
grandchild.name = "Eddie";
grandchild.print();

Also see:

Eduard Florinescu
  • 973
  • 2
  • 12
  • 32
Aadaam
  • 1,437
  • 9
  • 12
  • I Edited because function F didn't had {} and object had ;(semicolon) instead of ,(comma) now it doesn't give any error in console. It works and I don't know why it now seems so simple. One of my coleague has Good Parts too, but in this case your example helped more. Thanks. – Eduard Florinescu Aug 17 '12 at 23:27
2

The hilarious expert @venkat_s shares an analogy to grasp prototypal inheritance.

Here is a sample of his humor, "The thing about JavaScript is, it doesn't yell at you. It is your friend. It wont tell you when something is wrong, it will just stop working. Stop calling you"

For inheritance he continued, "The prototype is like a backpack - to the object. For everything in JavaScript that is an object - it has a backpack, and you can put stuff in it. And all your objects can access it."

Hope that helps.

Jack Stone
  • 1,151
  • 10
  • 11
  • I suppose the backpack is the prototype ? – Eduard Florinescu Aug 19 '12 at 09:32
  • Yes, apologies for the brevity. He went on to expand the analogy to multiple inheritance - "It is like having a backpack and a wallet.", "You just put stuff in each.", "Some times the error with prototypal inheritance is that... you can lose your wallet, and you have to get it back." This is the challenge that you may face, but is basic oo design pattern to solve. – Jack Stone Aug 19 '12 at 18:08
2

Forget code. The simplest explanation.

Function constructors build objects. In JS, functions are themselves objects which can have properties. Every function has a prototype property which can contain any object. You can set any constructors prototype easily on the fly. If you want to ruin arrays for instance,

Array.prototype = {
    oneTrueMethodToRuleThemAll: function(){
        alert('arrays are now hosed');
    }
}

The prototype object is basically a fallback that gets checked by instances when you try to reference a property they don't have. If the prototype object doesn't have that method, its constructor's prototype object gets checked for the method. That's the chain that gets followed.

So it's not really about inheritance. It's about, "Oh, you don't have that, well does your mother have it in her prototype bag? No? How about her grandmother? No? Then how about .. until we get to Eve, or the Object constructor's prototype which is where the buck always stops.

So it's not that your instances pick up or retain the stuff in the prototype. It's just that when JavaScript calls a method of an object there is fallback process for checking the object->constructor.prototype chain to see if the unknown method can be found. And that's why when you change a constructor prototype, all existing instances "get" that method. They don't really get anything at all. It's their fallback set of objects for lookup that gets the new method.

Erik Reppen
  • 6,243
  • 31
  • 34