我是 Javascript
的新手Object Oriented Programming
。我需要写一个JS
class
,可以是inherited
。完整的类可以是inherited
。以及每当 document
是 ready
,它被调用。
我正在尝试以下方式:
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/