Difference between a class and an object in Javascript

后端 未结 3 1062
被撕碎了的回忆
被撕碎了的回忆 2021-01-04 01:42

What\'s the difference between

var myView = function () {
//something goes here
};

and

var myView = function () {
//somet         


        
3条回答
  •  生来不讨喜
    2021-01-04 02:16

    There are no classes in javascript.

    As you mentioned, your first example would be for a re-usable object, whereas your second example is just for a singleton object.

    The main difference here is that you're invoking that function immediately in the second example and it returns an object to you, whereas you need to explicitly invoke the first function each time using something like a=new myView() it's the () that's providing that invocation.

    I use your 2nd example (known as crockford's module pattern) for one off page related tasks, and the first example for re-usable components within that page (some element generated many times with handlers etc)

    Also read about protoypal inheritance so you can understand how to effectively use the first example for writing better performing javascript code.

提交回复
热议问题