oop - Difference between JavaScript methods structure -


what difference between method structures/callings?
see different method structures , can not understand benefits of each are.

var obj = {     some_method: function(){         return 'this works';     } }  var obj2 = function(){     return {         some_method: function(){             return 'this works too';         }     } }  console.log(obj.some_method());  var obj3 = new obj2(); console.log(obj3.some_method()); 

both of them return should, here's jsfiddle, in case should use each of them?

the first 1 resembles singleton, i.e. cannot have multiple objects of same type distinct state. it's possible have 1 actual animal in entire application instead of many.

a more practical example, consider page. there multiple posts, each own state (what comments have, text have, being edited , on). if did var post = means there can 1 post. suspect have ad-hoc jquery manipulate multiple posts in singleton not doing object oriented modeling of problem anyway.


the second 1 using constructor function incorrectly, created objects not instances of obj2 object. use constructor like:

function obj2() {    //initialize fields here }  obj2.prototype.somemethod = function(arg) {      return this.state + arg; }; 

the reason returning object literal works in constructor constructor allowed return objects of type. doesn't make sense make constructor return objects.

you typically need objects grouping related static functionality (behavior, no prolonged data) or dictionary/map/associative array (data no behavior).


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -