Guesser
Guesser

Reputation: 1857

Reference Javascript object method when instantiating object

a = function(x){

this.c = x;

this.c();

}

a.prototype.b = function () {

alert("B");

}

a.prototype.c = function () {

//overwrite this

}

var z = new a(this.b);

I know using this.b is wrong but is there anyway I can reference an objects method and pass it as an argument when instantiating the object?

I know the object instance doesn't exist yet but the prototypes do.

I can't paste the context as it's far too complicated I'm afraid. Basically I want to overwrite prototype.b on some occasions and do that at the instantiation point rather than afterwards. Mainly for prettier code. But if can't be done no worries.

Upvotes: 0

Views: 31

Answers (1)

user8897421
user8897421

Reputation:

You would need to reference it from the constructor.

a = function(x) {
  this.c = x;
  this.c();
}

a.prototype.b = function() {
  alert("B");
}

var z = new a(a.prototype.b);

or maybe it would be nicer to send the name of the desired method, and have the constructor do it.

a = function(x) {
  if (x in a.prototype) {
    this.c = a.prototype[x];
    this.c();
  }
}

a.prototype.b = function() {
  alert("B");
}

var z = new a("b");

Upvotes: 1

Related Questions