简体   繁体   English

在Javascript中设置不带__proto__的函数原型

[英]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/ 功能演示: http : //jsfiddle.net/juwt5o97/

This allows me to pass the constructor along and modify it before calling new . 这使我可以在调用new之前传递构造函数并对其进行修改。 However, I don't want to use __proto__ or Object.setPrototypeOf() . 但是,我不想使用__proto__Object.setPrototypeOf() Is there a "proper" way of doing this? 是否有“适当”的方法来做到这一点?

If you want to extend the prototype of your first class (so that instances inherit the methods) you can do so with Object.create : 如果要扩展第一个类的原型(以便实例继承方法),则可以使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM