繁体   English   中英

如何在JS中重新定义标准函数的构造函数?

[英]How to redefine constructor of standard function in JS?

所以,我想用输入参数重新定义HTMLButtonElement的构造函数。 我知道如何不使用args:

var CButtonPrototype = Object.create(HTMLButtonElement.prototype);
CButtonPrototype.createdCallback = function()
{
  alert("call");
  this.setAttribute("class", "some class");
  this.value = 0;
  this.innerHTML = "some text";
};

var CButton = document.registerElement('cbutton', {
  prototype: CButtonPrototype
});

var myButton = new CButton();

它是可行的,但我想使用此类,如var myButton = new CButton(arg 1, arg 2, etc); 此方法不允许我执行CButtonPrototype.createdCallback = function(arg 1, arg2) 我该如何解决? 也许您知道另一种方式?

谢谢\\ o /

如果您需要扩展此类型,请考虑以下因素:

CButton.prototype.test = function()
{
    console.log(arguments);
}

CButton.prototype.test2 = function(num, str, bool)
{
    console.log(num + ' ' + str + ' ' + bool);
}

myButton.test(20, 'hello', true); //call test function with parameters
myButton.test2(20, 'hello', true); // still the same

关于您的原始问题:

您不能插入参数,因为此“函数”仅是系统函数的委托...在您的情况下,是对象c'tor。

要测试它,您可以尝试使用参数-js中每个函数内部的一个特殊数组,代表该函数的参数:

var CButtonPrototype = Object.create(HTMLButtonElement.prototype);
CButtonPrototype.createdCallback = function()
{
  console.log(arguments); // print arguments to the console screen
  this.setAttribute("class", "some class");
  this.value = 0;
  this.innerHTML = "some text";
};

var CButton = document.registerElement('cbutton', {
  prototype: CButtonPrototype
});

var myButton = new CButton();

运行此代码-您将看到一个空数组-主要是因为您的c'tor调用'new CButton()'没有参数。 尝试插入参数,您将得到一个错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM