Yoorek
Yoorek

Reputation: 1003

JavaScript 'new' weird usage

If a constructor function is just a function that with 'new' returns object why instead of usual:

function One(message){
    this.message = message;
}

One.prototype.getMessage = function() {
    console.log(this.message);
}

we do not do:

function Two(message){
    return {
        message: message,
        getMessage: function() {
            console.log(this.message);
        }
    }
}

The usage is the same and result (in this simple case) the same:

var o1 = new One('One');
o1.getMessage();

var o2 = new Two('Two');
o2.getMessage();

I got two answers:

  1. 'prototype' of o2 is Object so, o2 instanceof Two returns false
  2. function getMessage is defined for each instance of Two separately but One is defined only in One's prototype.

Any other answers "why it's wrong"?

Upvotes: 1

Views: 99

Answers (3)

Eduard Jacko
Eduard Jacko

Reputation: 2151

Do 100x new Two(message) and you will create 100x getMessage function. So thats quite a memory impact if the get message become quite complicated. If you write it in to prototype, you will get only one function no metters how many times you will create a new instance of Two. Accessing a prototype is a little bit slower than direct accessing. If its singleton, you don't need prototype. If its factory, please go with prototype.

FYI: Im using es6, so prototype everywhere :)

Upvotes: 0

stackunderflow
stackunderflow

Reputation: 3873

What I know is that when you add property to prototype you are ensuring that this property is shared between all instances, thus it is memory optimization if you will have one object instantiated hundred times.

If you come from typical OOP like c#, then adding a property to a prototype is similar to some extent to defining a static field

Public static string msg = " hello";

Upvotes: 0

TGH
TGH

Reputation: 39258

Option1 associates the method with the type, so that you don't have to redefine the function every time you need a One type. This results in better performance and less memory usage.

In option 2 you are redefining a dynamic object every time you instantiate the object.

Upvotes: 3

Related Questions