ObiHill
ObiHill

Reputation: 11876

Dynamic Function Call for Prototype Functions

I have to make a bunch of .prototype declarations within a function and would like to add some dynamism to reduce the size of my code.

Here is some pseudo code for what I need to do:

window.myClass = function(){
  var object_type = getObjectType();
  if (object_type === 'NodeList')
  {
     NodeList.prototype.func_name = function(){
         //some code 
     }
  }

  if (object_type === 'HTMLCollection')
  {
     HTMLCollection.prototype.func_name = function(){
         //the same code again 
     }
  }
}

I would like to change this so I can make these declarations dynamic, kind of like this:

window.myClass = function(){
  var object_type = getObjectType();
  object_type.prototype.func_name = function(){
     //some code
  }
}

Is this possible?

EDIT

I forgot to mention that I would love to keep all my functions within the scope of window.myClass

Upvotes: 2

Views: 301

Answers (2)

user663031
user663031

Reputation:

Without going into details about what are you trying to accomplish or whether it's a good idea or there are better ways to do it, just based on your posted code, all you need to do is define "some code" as a funtion and assign it to whatever you want:

window.myClass = function(){
  function someCode() { /* some code */ }

  var object_type = getObjectType();
  if (object_type === 'NodeList')
  {
     NodeList.prototype.func_name = someCode;
  }

  if (object_type === 'HTMLCollection')
  {
     HTMLCollection.prototype.func_name = someCode;
  }
}

But you don't really need the if statement, because you can just do

window.myClass = function(){
  function someCode() { /* some code */ }

  var object_type = getObjectType();
  window[object_type].prototype.func_name = someCode;
}

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382132

In your case you can simply do

window[object_type].prototype[func_name] = function(){...

But be careful that you seem to be engaged in modifying objects you don't own. There's probably a better possible design for your application.

Upvotes: 1

Related Questions