覆盖Object.create继承模式中的构造函数

时间:2014-02-18 19:25:44

标签: javascript inheritance prototype

我想要一个子类'构造函数在执行它之前调用它的父元素的构造函数,并使用Object.create模式。

使用new Parent()

var Parent = function(){ console.log( 'Parent' ) };
var Child  = function(){ console.log( 'Child' ) };
Child.prototype = new Parent(); // Prints 'Parent'
var child = new Child(); // Prints 'Child'

使用Object.create

var Parent = function(){ console.log( 'Parent' ) };
var Child  = function(){ console.log( 'Child' ) };
Child.prototype = Object.create( Parent.prototype );
var child = new Child(); // I'd like this to print 'Parent' then 'Child'

这甚至可能吗?我可以在Parent.call( this )构造函数中添加Child之类的内容吗?

2 个答案:

答案 0 :(得分:1)

  

我可以在Child构造函数中添加Parent.call( this )之类的内容吗?

是的,就这样做。

var Parent = function(){ console.log( 'Parent' ) };
var Child  = function(){ Parent.call(this); console.log( 'Child' ) };
Child.prototype = Object.create( Parent.prototype ); // should print nothing
var child = new Child(); // prints 'Parent' then 'Child'

答案 1 :(得分:0)

好问题。不过你已经回答了。

var Parent = function(){console.log('Parent')};
var Child = function(){
  console.log('Child')
  Parent.call(this);
};
Child.prototype = new Parent();
var child = new Child();
Firebug控制台中的

生成

Parent
Child
Parent
Object { }

作为输出。

相关问题