Javascriptprototype.constructor没有被调用

标签 javascript jquery oop

我是 Javascript 的新手Object Oriented Programming 。我需要写一个JS class ,可以是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调用到达。然而并没有被调用。

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

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

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

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

最佳答案

您遇到的问题是该行没有按照您的想法进行操作:

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();

关于Javascriptprototype.constructor没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21502019/

相关文章:

jquery - 如何排除 jQuery DataTable 中的最后一列

javascript - 如何在 javascript/Jquery 中重置计时器?

javascript - 使用 Snap.Select 时 SVG 未捕获类型错误

不需要 node.js 的 javascript 包管理器

javascript - AJAX 返回代码 200 但引发错误

javascript - 如何在第二个堆叠模式对话框中包含 jquery ui 小部件?

javascript - 试图理解对象原型(prototype)

c++ - Pop() 礼仪

ios - iOS 中 Setter 和 Getter 的来龙去脉?

javascript - 在 HTML 中传递多个参数 onMouseover 事件处理程序