2013-12-14 82 views
0

我正在使用这种类型的代码进行继承。问题是我在设置prototypeB时出现错误,因为new A()尝试访问params.param,当设置B.prototype时,paramsundefined。如何处理它?或者我应该使用另一种模式来模拟js中的继承?JavaScript - 构造函数参数和原型继承

function A(params) { 
    this.param = params.param; // this will throw error when set up B prototype 
} 

function B(params) { 
    A.call(this, params); // this is ok 
} 

B.prototype = new A(); // this is bad, A need some parameters 
+1

的可能DUP http://stackoverflow.com/questions/7533473/javascript-inheritance-when-constructor-has-arguments和http://stackoverflow.com/questions/7785955/inherit-parent-constructor -arguments和http://stackoverflow.com/questions/3601932/how-do-i-call-an-inherited-javascript-constructor-with-parameters – jfriend00

回答

0

你可以这样做,不会得到问题。

var EmptyFunc = function() {}; 
EmptyFunc.prototype = A.prototype; 

B.prototype = new EmptyFunc;