Should functions be attached to object or its prototype?

askstackoverflow :

I am learning javascript and I am wondering about the concept of functions and prototypes inside an object.

My understanding of the concept

As I understand it, functions should be attached to object's prototype in order to allocate less memory.

For example (if what I said is true), both version will do the same job but second version will allocate less memory:

var collectionOfObjects = [];
for(var i=0; i<1000; i++){
    collectionOfObjects.push({id: 2, sayHi: function(){console .log('hi')}})
}
//vs
function Foobar(id){
    this.id = id || 0;
}
Foobar.prototype.sayHi = function(){
    console.log('hi');
}
var otherCollection = [];
for(var i=0; i<1000; i++){
    otherCollection.push(new Foobar());
}

Question

//this attaches sayHi function to the object instead of its prototype
var foobar = {
    id: 0,
    sayHi: function(){
        console.log('Hi');
    }
}

Since I shouldn't use __proto__, how do I attach sayHi function to foobar's prototype instead of foobar object? I assume that adding sayHi to Object.prototype isn't a good solution as it would add sayHi function to every object.

Alex Wayne :

The prototype chain is setup via the new keyword, a class or Object.create(). Either way, it's set when the object is created.

So you already know one way, which is is to add functions to the prototype of a constructor function and instantiate with new.

The modern way would be to use a class, but you specifically mention legacy code here, so I'm going to assume that's out for purposes of this discussion.

The last way is to use Object.create() which gives you an object with some prototype:

var myProto = {
  // There is only one of this function, ever.
  sayHi: function() {
    console.log('hi');
  }
}

var otherCollection = [];
for(var i=0; i<1000; i++){
    var obj = Object.create(myProto)
    obj.id = i // or other custom setup.
    otherCollection.push(obj);
}

That said, in modern javascript engines having unique functions per object is not a big deal. I've worked on some pretty large javascript apps and memory usage due to the number of function instances has not ever been a performance bottleneck at all.

In modern React with functional hooks, for instance, it would be incredibly cumbersome (if not impossible in some cases) to avoid creating hundreds of new functions on every render. It's designed to be that way and it still performs very well. And if it doesn't perform well, it's never due to too many functions.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19852&siteId=1