1
#1 (object) 
function Person(f){
      this.firstname = f;

      alert(this.firstname);
    }
    var me = new Person('benny');


#2 (function) 
    function Person(f){
       alert(f);
    }
    Person('benny');

Im new in js oop, I have knowledge of oop in PHP

My question is what's different between 1st one and 2nd one?

in php, if I create an obj, i will start with class{}

in JS, it seems like you can also create an obj var obj = {} OR like create it like a function?

can someone enplane how it works?

winner_joiner
  • 12,173
  • 4
  • 36
  • 61
Benjamin W
  • 2,658
  • 7
  • 26
  • 48
  • check out this https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor – winner_joiner Sep 09 '16 at 15:07
  • First: In js you are always in an object context. Short Answer to: #1 vs #2 you can do `alert(me.firstname);` that is not possible on the #2. But some should drop you an good link to an page, where this all is explaint in detail, i watched yesterday a vid that was about 2 hours only about that topic OOP in javascript – JustOnUnderMillions Sep 09 '16 at 15:09
  • Read this: http://stackoverflow.com/questions/21321962/javascript-the-good-parts-function-prototypes-vs-object-prototypes – JustOnUnderMillions Sep 09 '16 at 15:10
  • And this: http://stackoverflow.com/questions/1441212/javascript-instance-functions-versus-prototype-functions – JustOnUnderMillions Sep 09 '16 at 15:11
  • Finally this: http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript – JustOnUnderMillions Sep 09 '16 at 15:11
  • [Here](http://stackoverflow.com/documentation/javascript/1668/creational-design-patterns#t=201609091540303150697) you could find a bit of documentation. And let me correct you. In PHP you can't create an object with *class*, an object is a class instance, and you create it through the *new* operator. In javascript pretty everithing is an object and object are bare hashmaps. – Mario Santini Sep 09 '16 at 15:43
  • In your first example you're using the function as a constructor function. In the second example, you're not. Many things in Javascript are decided by the way you *call* functions, not necessarily by the way you *define* them. – deceze Sep 09 '16 at 15:47

1 Answers1

1

The first is a constructor function and the second is just a plain function with a capital letter.

The constructor function is a way of creating data types. JavaScript offers prototypal inheritance.

Person.prototype.newmethod = function(){...};

There is a class keyword in the new JavaScript version. You could use also TypeScript. It may make more sense to you.

Stoycho Trenchev
  • 557
  • 4
  • 12