0

所以,我想用输入参数重新定义 HTMLButtonElement 的构造函数。我知道如何在没有参数的情况下做到这一点:

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/

4

1 回答 1

1

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

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()' 没有参数。尝试插入参数,你会得到一个错误。

于 2014-11-29T19:51:30.103 回答