Difference between a class and an object in Javascript

后端 未结 3 1061
被撕碎了的回忆
被撕碎了的回忆 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.

    0 讨论(0)
  • 2021-01-04 02:33

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

    This is function expression without being executed. And var myView = function () { //something goes here return { a: x, b: y }(); This function expression gets executed due to parenthesis "()" place after function resulting in return of Object.

    Again New keyword use for creating constructor and can not be applicable for Object.

    0 讨论(0)
  • 2021-01-04 02:36

    Javascript uses prototypal inheritance, so there are no classes per se. Everything is an object; it's just that some objects have a common parent object whose methods/variables will be found when name resolution looks up the prototype chain.

    Your first code snippet creates an object called myView whose type is a function. Your second snippet defines an anonymous method which returns an object (with two properties, a and b) and then immediately calls this method, assigning the result to myView. So in this second case, myView is an object with two self-defined properties.

    It may help you to read Douglas Crockford's description of prototypal inheritance in Javascript, as it sounds like you're a little fuzzy on the details.

    0 讨论(0)
提交回复
热议问题