Javascript 如何从类构造函数中的参数继承方法

Javascript 如何从类构造函数中的参数继承方法,javascript,inheritance,Javascript,Inheritance,所以我从一个文件中导出一个对象,并尝试继承它的所有方法并添加 function childClass (model) { this.model = model } childClass.prototype.foo1 = function(){ this.model.Something1(); } childClass.prototype.foo2 = function(){ this.model.Something2(); } 理想情况下,当有人从childClass实例化一个对象时,我

所以我从一个文件中导出一个对象,并尝试继承它的所有方法并添加

function childClass (model) { 
this.model = model
}

childClass.prototype.foo1 = function(){
this.model.Something1();
}

childClass.prototype.foo2 = function(){
this.model.Something2();
}


理想情况下,当有人从childClass实例化一个对象时,我希望它继承该类正在使用的基本模型对象的所有方法,这样我就可以不调用obj.model.function1而直接调用obj.function1。

您可能正在寻找一种委托模式,可以实现为:

defineDelegate(delegatee, method) {
    childClass.prototype[method] = function() {
        var delegatee = this[delegatee];
        return delegatee[method].apply(delegatee, arguments);
    };
}
现在你可以说

defineDelegate('model', 'Something1');
defineDelegate('model', 'Something2');
这需要清理和推广,但我希望你能理解

如果出于某种原因,您希望将
模型上的所有方法委派给

Object.keys(modelClassPrototype)
    .filter (function(k) { return typeof modelClassPrototype[k] === 'function'; })
    .forEach(function(k) { defineDelegate('model', k); })
;

你实际上是在问如何在儿童课上混合模型

function childClass (model) { 
 Object.keys(model).forEach(function(key) {
   childClass.prototype[key] = model[key].bind(model);
 });
}

var m = { create: function() {console.log(this);}};

var c = new childClass(m);
c.create();

create方法的
this
上下文将是model,如果您不想将其绑定到model,那么就删除bind函数

,那么为什么不从模型类继承而不是包装它呢?搜索“delegation”。顺便问一下,你的意思是说
this.model.Something1()
(在
model
something1
之间有一个点?我确实感谢了,只是在文本编辑器中自由键入了一些内容。我不得不承认@torazaburo的解决方案要好得多。只是出于好奇,这样做会有什么不同。something1=model.something1在childClass构造函数中?这不会起作用,因为它不会通过across将
这个
正确地保存起来。(它还将把属性放在
子类
的每个实例上)model.something1是一个函数而不是一个方法,如果您将函数直接分配给此对象,函数的上下文将更改为ChildObject创建的对象的实例,而不是模型,您可能不希望这样