1

I was reading about Object Oriented JS, and trying to understand whether prototype based inheritance is best in my case. I just read Eric Elliot post on the superiority of this method over classical pattern here

In my case, I have to model, say 10,000 instances of a type or class called Shape . I need each object hold on to its state, say size. Would using clone to extend the prototype (2nd method in Eric's post) causes the methods to clone too?? From his example,

var proto = {
  hello: function hello() {
    return 'Hello, my name is ' + this.name;
  }
};

var george = _.extend({}, proto, {name: 'George'});

does in the above case, creating 10,000 instance would clone hello into all the instances?

If that is the case, what is the best approach for me. My type/class holds 10 primitive values, and more act as a holder of data than abstracting behavior. Requirements,

  1. Each instance hold on to private data.
  2. Have some common methods to get/set those data (or just properties)
  3. Easy to convert to Json
bsr
  • 57,282
  • 86
  • 216
  • 316

1 Answers1

1
var george = _.extend({}, proto, {name: 'George'});

In above code, you are using underscore's extend (you need underscore lib) method. If you create object like this.

for (var i = 0; i < 1000; i ++) {
 var obj = _.extend({}, proto, {name: 'George'});
}

all 1000 objects will be like this.

{
  {name: 'George'},
  hello: function hello() {
    return 'Hello, my name is ' + this.name;
  }
};

But below two methods share same hello function among all 1000 objects. So pick any one of this as per your wish.

classical approach.

var proto = function (name) {this.name = name || ""};

proto.prototype.hello = function hello() {
    return 'Hello, my name is ' + this.name;   }

var p2 = new proto({name: "george"});

p2.hello() //"Hello, my name is george"

using Object.create()

var proto = {
  hello: function hello() {
    return 'Hello, my name is ' + this.name;
  }
};

var p = Object.create(proto, {name: {value: "george"}})

p.hello() //"Hello, my name is george"

You should have clear understanding before start using Object.create. It is only supported on modern browsers. Below links can help you to understand this more

link 1, link 2, link 3

user10
  • 5,186
  • 8
  • 43
  • 64
  • THis is one SO answer by Eric http://stackoverflow.com/questions/1450582/classical-vs-prototypal-inheritance about the same. Anyway, above look simpler. – bsr Oct 08 '13 at 15:59