1

I want to create a constructor that has an object as its prototype.

For example:

var constructor=function(){
  this.foo=bar;
}

var constructorProto={
  method:function(){}
}

constructor.__proto__=constructorProto;

constructor.method();
new constructor;

Functional demo: http://jsfiddle.net/juwt5o97/

This allows me to pass the constructor along and modify it before calling new. However, I don't want to use __proto__ or Object.setPrototypeOf(). Is there a "proper" way of doing this?

17
  • 1
    Why do you think Object.setPrototypeOf() is not "proper"? Commented Mar 19, 2015 at 20:51
  • prototypes are not static methods, so it's confusing what you want... you can just say constructor.method=constructorProto.method;, or use Extend or Object.create() to copy. Commented Mar 19, 2015 at 20:53
  • I remember reading somewhere that it shouldn't be used, maybe I got it mixed up with __proto__. Regardless, it's ES6 and I'd prefer if there's a method that works with ES5. Commented Mar 19, 2015 at 20:54
  • "I remember reading somewhere that it shouldn't be used..." I think you probably missed the point. They're likely not saying that that particular way of changing the prototype shouldn't be used. They're likely saying you shouldn't change it at all. Commented Mar 19, 2015 at 20:56
  • @dandavis The constructor may be created multiple times, so I don't want to recreate the methods for each constructor. Commented Mar 19, 2015 at 20:57

1 Answer 1

1

If you want to extend the prototype of your first class (so that instances inherit the methods) you can do so with Object.create:

var ClassA=function(){
  this.foo='bar';
}

var protoObject = {
  method:function(){alert('t');}
}

ClassA.prototype = Object.create(protoObject);

new ClassA().method();

If you want to just attach static functions to the first function, then you can do it like this:

for (var property in protoObject) {
  if (typeof protoObject[property] == 'function') {
    ClassA[property] = protoObject[property];
  }
}

ClassA.method();
Sign up to request clarification or add additional context in comments.

7 Comments

This is allowing him "to modify it before calling new". He just can't invoke it before calling new. That would... not involve the prototype at all. It would just be a static property...
but i think he want to run constructor.method() before an instance is created... it's not a clear question.
Eh, I'll update my example then, but if that's what he wants... he's misunderstanding how the prototype works
i'm pretty sure that's the case, but i like how you handle both potentials.
Thanks. :) And thanks for pointing out that I may have misunderstood what he was looking for.
|

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.