【问题标题】:Javascript inherit constructorJavascript继承构造函数
【发布时间】:2012-07-26 00:06:24
【问题描述】:

正如我可以做的那样,让子继承父而不像这样改变子代码构造函数:

var parent = function(params){
    this.params = params;
}

var child = function(){}

var childObj = new child({one:1,two:2});

console.log(childObj.params) //should show params

【问题讨论】:

  • 你不能。您应该手动调用父方法(构造函数或泛型函数)

标签: javascript inheritance constructor


【解决方案1】:

你不能。那将如何工作,您传递给函数的参数(对它们没有任何作用)无法从外部获得......

function child(p) {
    parent.call(this, p);
}

在不修改构造函数的情况下,你唯一能做的就是手动设置它们:

var childObj = new child();
childObj.params = {one:1,two:2};

// or, if you want all child objects to inherit them:

child.prototype.params = {one:1,two:2};

【讨论】:

  • 感谢回复,我想它会选择第一个选项:parent.call(this, p);
猜你喜欢
  • 2013-09-17
  • 1970-01-01
  • 2012-06-26
  • 1970-01-01
  • 1970-01-01
  • 2017-02-25
  • 2014-09-02
  • 2011-12-26
  • 1970-01-01
相关资源
最近更新 更多