0
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.

1
  • Note that this in your var z = new a(this.b) is either the global window object or undefined, replace with a.prototype.b although it's not clear why you would ever actually want to do this. What are you actually trying to accomplish here? Commented Nov 7, 2017 at 20:01

1 Answer 1

1

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");

Sign up to request clarification or add additional context in comments.

1 Comment

If a doesn't yet exist, then how are you invoking?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.