0

Im starting to learn some JS and I want to understand how should I create class with inheritance,after I read some articles and post in SO Im little bit confuse about how to implement it in the right... i've created the following very simple example to understand it better but Im not sure that this is the right way therefore I write this post.

1. since Im coming from OOP language this is the right way to create class with two different object that using the same functionality ?

http://plnkr.co/edit/NCJs9jdKP5o0mwp6SuBD?p=info

2. In some JS files I saw the regular way to create function which I understand

function fnName(){
console.log("test");
}

and in some files I saw function like following

say:function(){
 console.log("say something")
}

what are the difference between those two ways to define function?

I tried sometimes to use it and I got error function name is missing,any idea when I can use this and when not ?

  • 1
    http://addyosmani.com/resources/essentialjsdesignpatterns/book/ – Abhitalks Nov 30 '14 at 09:21
  • @abhitalks- Thanks, which section should I look for? –  Nov 30 '14 at 09:26
  • 1
    All of it. Start from page 1. It will help you understand that there are many patterns. – Abhitalks Nov 30 '14 at 09:29
  • @abhitalks-Thanks,about the second question when should I use the second function approach?just when I use object or there is some more use cases ... –  Nov 30 '14 at 09:31
  • Object creation, inheritance, mix ins, constructor functions and prototype are covered here: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Nov 30 '14 at 10:45

1 Answers1

0

The first is just a standard function. Generally creating it like that will add it to the window object.

The second is creating a function on an object literal.

There's lots more to it than that but it should get you started.

An example object literal :

var Swapper = {
    // an array literal
    images: ["smile.gif", "grim.gif", "frown.gif", "bomb.gif"],
    pos: { // nested object literal
        x: 40,
        y: 300
    },
    onSwap: function() { // function
        // code here
    }
};

You would then call it:

Swapper.onSwap();

Dave Walker
  • 3,498
  • 1
  • 24
  • 25
  • Thanks Dave for answering the second question,can you please elaborate when typically you should use the second approach ? –  Nov 30 '14 at 09:25
  • 1
    They really aren't comparable to be fair. The first would be a global function, or a helper function, which for the most part are to be avoided. Having a function on an object, or even better on a class, is preferable. You really need to read up more on Object Oriented design to get a better understanding here. – Dave Walker Nov 30 '14 at 10:18