【问题标题】:Javascript prototype.constructor not being calledJavascript原型。构造函数没有被调用
【发布时间】:2014-02-01 18:44:26
【问题描述】:

我是Javascript Object Oriented Programming 的新手。我需要写一个JSclass,可以是inherited。完整的类可以是inherited。只要documentready,它就会被调用。

我正在尝试以下方式:

alert('reached');
var Hello = new VeerWidget();

function VeerWidget(){}

VeerWidget.prototype.constructor = function()
{
    $(document).ready(function(){
        alert('called');
    });
}

上面的代码我在xyz.js

我的期望是:一旦页面加载,popup reached 就会被调用,然后popup 被调用

但这不起作用。 popup with reached 被调用。但是 called 没有被调用。

但是当我尝试这种方式时:

alert('reached');
var Hello = new VeerWidget();

function VeerWidget()
{
    $(document).ready(function(){
        alert('called');
    });
}

一切顺利。但我需要继承VeerWidget。如何做到这一点?

【问题讨论】:

  • 如果您想了解为什么它不能像您预期的那样工作,请研究 javascript 变量“提升”。
  • 更改顺序。您正在启动 Hellothen 设置构造函数。首先定义您需要在 VeerWidget 上定义的所有内容,然后然后创建实例
  • @rambocoder: 不起作用的原因与吊装无关。
  • @FelixKling:是的,但是查找它的建议很好,因为它是 second 示例起作用的原因:-)

标签: javascript jquery oop


【解决方案1】:

你遇到的问题是这条线没有做你认为它做的事情:

VeerWidget.prototype.constructor = function()

它的作用是为所有实例可见的属性设置一个值。

实例的构造函数实际上是 VeerWidget 函数,无论你做什么都不会改变,所以你的代码应该是这样的:

alert('reached');
var Hello = new VeerWidget();

function VeerWidget(){
    $(document).ready(function(){
        alert('called');
    });
}

至于继承,我不完全确定你在追求什么,但它可能看起来像这样:

function InheritingWidget() {
    VeerWidget.call(this);
}

InheritingWidget.prototype = Object.create(VeerWidget.prototype);
InheritingWidget.prototype.constructor = InheritingWidget;

var inheritingHello = new InheritingWidget();

【讨论】:

    【解决方案2】:

    通过在主构造函数的末尾添加这一行来简单地执行原型的构造函数:

    if(typeof this.__proto__.constructor === 'function') this.__proto__.constructor();
    

    最终的结果是:

    VeerWidget.prototype.constructor = function(parent) {
        var message = parent.getMessage();
        $(document).ready(function(){
           alert(message);
        });
    }
    
    alert('reached');
    var Hello = new VeerWidget();
    
    function VeerWidget()
    {
        if(typeof this.__proto__.constructor === 'function') this.__proto__.constructor();
    }
    

    注意:你可以像这样传递父函数来访问它的方法:

    VeerWidget.prototype.constructor = function(parent) {
        var message = parent.getMessage();
        $(document).ready(function(){
           alert(message);
        });
    }
    
    function VeerWidget()
    {
        this.getMessage = function() {return 'called';};
        if(typeof this.__proto__.constructor === 'function') this.__proto__.constructor(this);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 2016-07-12
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-06
      相关资源
      最近更新 更多