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 post
s, each own state (what comment
s 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 object
s.
you typically need object
s grouping related static functionality (behavior, no prolonged data) or dictionary/map/associative array (data no behavior).
Comments
Post a Comment