一行代码中的实例和原型

时间:2015-03-28 15:14:31

标签: javascript instance prototypal-inheritance

设置情况的示例代码:

function Parent()
{
    //code
}

function Child()
{
    //code
}

Child.prototype = Object.create(Parent.prototype);
var objChild = new Child();

是否可以将最后两行写入一个?

编辑:在我写这种代码的同时,我想到了这一点。我不是在这里特定的事情之后。只是想知道是否可能。

1 个答案:

答案 0 :(得分:0)

您可以将其包装在函数中并传递父类。

function Parent()
{
    //code
}

function Child(parentClass)
{

  function ChildObj() {

  }

  ChildObj.prototype = Object.create(parentClass.prototype);

  return new ChildObj();
}


var objChild = Child(Parent);