Difference between a constructor and an Object

前端 未结 4 691
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 07:19

I definitely need some light on this.

What\'s the diference between:

var MY_APP = function(){
    this.firstMethod = function(){
       //something
          


        
4条回答
  •  渐次进展
    2020-12-09 07:40

    The first is a function, the second is an object literal. Since Functions in JS are first class objects, a function can have properties on it, just like any other object can.

    Typically, if you want to create a "class" that you might be familiar with from classical inheritance languages, you would do something like

    function MyClass() {...}
    

    as is documented here http://www.crockford.com/javascript/inheritance.html

    To answer the question posed in your edits, you would use them both in different situations. Object literals are used to pass configurations around. A typical usage pattern would be a method that accepts an object literal like so

     something.init({
          length: 10,
          height: 10,
          text: 'some text'
     });
    

    and so on.

    You could use something similar to your first example when creating a namespace. Javascript has some interesting language features in that you can have so-called "self-invoking functions" that are of the form:

    var myApp = (function(){
        var firstMethod = function() {...}
        ...
    })();
    

    the motivations behind doing something like this are detailed here
    http://sparecycles.wordpress.com/2008/06/29/advanced-javascript/

    You can also investigate the differences via your favorite javascript debugging console. In firebug and chrome, I did the following:

    var ol = {}; ol.prototype;

    var fn = function(){}; fn.prototype;

    the first line prints undefined, the second returns a prototype with a constructor of 'function'

提交回复
热议问题