Leo Jiang
Leo Jiang

Reputation: 26095

Setting the prototype of a function without __proto__ in Javascript

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?

Upvotes: 1

Views: 139

Answers (1)

bvaughn
bvaughn

Reputation: 13487

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

Upvotes: 1

Related Questions