Use prototype object correctly

Hi

I have a JavaScript program written with object literal syntax:

var MyJsProgram = {

    someVar: value1,
    somevar2: value2,

    init : function() {
        //do some initialisation
    },

    libraryFunction : function() {

    },

    getStyle : function() {

    },

    extend : function() {

    }
}

You can run multiple instances of this script at the same time. Should I move generic methods to myJsProgram object prototype? If so, is the syntax correct?

 var MyJsProgram = {

    someVar: value1,
    somevar2: value2,

    init : function() {
        //do some initialisation
    },

    //more methods/members here that are unique to each instance
}

myJsProgram.prototype = {
    //all shared methods here
}

?

+3
source share
2 answers

No, this syntax is incorrect (no offense);)

You need to create an object to use its prototypes. That means you need a constructor (which is a function in JavaScript). Applies to your problem:

var MyJsProgram = function (value1, value2) {
    // "this" refers to the current instance of this object
    this.someVar = value1;
    this.someVar2 = value2;
    // do some initialization
};

Create a new object as follows:

var jsProgramInstance = new MyJsProgram(value1, value2);

Prototypes are instances of these objects. They are defined as follows:

MyJsProgram.prototype.someSharedMethodName = function () {
    // do shared method stuff here
    // (this.someVar and this.someVar2 are available here)
};

Use them like this (on your previously created instance):

jsProgramInstance.someSharedMethodName();

, , (- ):

MyJsProgram.prototype = {
    someSharedMethodName: function () {
        // ...
    },
    // ...
};
+2

,

// Make it a function, so you can make a new instance
var stdProgram = function(){};

// All shared methods go here
stdProgram.prototype = {
  echo: function(message){
    alert(message);
  },
  extend: function(key, value){
    this[key] = value;
  }
};

"",

// And here you can make instances for specific programs
var myFirstProgram = new stdProgram(),
    mySecondProgram = new stdProgram();

myFirstProgram.extend('unique', function(){ 
  alert('I am unique');
});

mySecondProgram.aVar = 'test';

, , :

myFirstProgram.unique();     // Should alert I am unique
mySecondProgram.unique();    // Should throw an error, unique is undefined

alert(mySecondProgram.aVar); // Should alert test
alert(myFirstProgram.aVar);  // Should echo undefined

myFirstProgram.echo('hi');   // Should alert hi
mySecondProgram.echo('hi');  // Should alert hi
+3

Source: https://habr.com/ru/post/1770728/


All Articles