【问题标题】:JavaScript Constructor Not Called未调用 JavaScript 构造函数
【发布时间】:2012-05-10 06:12:53
【问题描述】:

我有一个实现继承的函数:

inherit = function(base) {
    var child = function() { console.log('Crappy constructor.'); };
    child.prototype = new base;
    child.prototype.constructor = child;
    return child;
}

我想我可以这样使用它:

var NewClass = inherit(BaseClass);
NewClass.prototype.constructor = function() {
    console.log('Awesome constructor.');
}

但是当我像这样创建 NewClass 的新实例时:

var instance = new NewClass();

我收到消息 Crappy constructor. 正在打印到控制台。为什么构造函数不被覆盖?以及如何覆盖它?

【问题讨论】:

  • 对象继承自其构造函数的原型,而不是它们自己的。将方法添加到BaseClass.prototype 以查看差异。

标签: javascript inheritance constructor


【解决方案1】:

你返回child,这是一个打印Crappy constructor的函数。不管怎样,如果你调用那个函数,Crappy constructor 会被打印出来。

注意流程:

child = function to print 'crappy'
child.prototype.blabla = function to print 'Awesome'
inherit returns child

NewClass = child

现在,当您调用 NewClass 时,会调用 child。

除此之外,我认为您需要 child.constructor.prototype 而不是prototype.constructor。

编辑:请在 Javascript here 中查看更多关于继承的信息。

【讨论】:

  • 好的,我想我明白你的意思了。出于某种原因,我认为构造函数是一个实际的函数,它会在创建新实例时自动调用,这就是为什么我们要像我在 inherit 函数中所做的那样重写。
  • 是的,在某些语言中会出现这种情况,AFAIC python 和 php,但是 javascript 是一种基于原型的语言,而不是基于类的语言,所以设计的东西有点不同。请参阅编辑以获取链接。
猜你喜欢
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-20
  • 2014-01-29
  • 2017-04-13
  • 2015-06-27
相关资源
最近更新 更多