Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
    
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. –  World Engineer 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
1  
@WorldEngineer I edited the question to be only one –  Eduard Florinescu Aug 17 '12 at 22:46
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 1:11
show 8 more comments

3 Answers 3

up vote 6 down vote accepted

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:

share|improve this answer
    
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
add comment

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.

share|improve this answer
    
I suppose the backpack is the prototype ? –  Eduard Florinescu Aug 19 '12 at 9: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. –  ClintNash Aug 19 '12 at 18:08
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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