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

Javascript 如何在JS中重新定义标准函数的构造函数?,javascript,constructor,redefine,Javascript,Constructor,Redefine,所以,我想用输入参数重新定义HtmlButtoneElement的构造函数。我知道如何在没有args的情况下执行此操作: var CButtonPrototype = Object.create(HTMLButtonElement.prototype); CButtonPrototype.createdCallback = function() { alert("call"); this.setAttribute("class", "some class"); this.value

所以,我想用输入参数重新定义HtmlButtoneElement的构造函数。我知道如何在没有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(arg1、arg2等)。此方法不允许我执行
CButtonPrototype.createdCallback=function(arg1,arg2)
。我如何解决这个问题?也许你知道另一种方法


谢谢O/</P> < P>如果您需要扩展此类型,请考虑以下内容:

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

要测试它,您可以尝试arguments—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()”没有参数。尝试插入参数会出现错误。

谢谢您的快速回答:)我知道原型函数,但您能告诉我,是否有其他方法可以根据我的需要重载c-tor?使用prototype func更好吗?你自己的c'tor-没问题。基于dom设置的重写c'tor。。。没有那么多。你们能分享一下你们对这种需求的想法吗?我想要一个有按钮方法的类。我之前尝试过:
函数CButton(buttonName,functionName,buttonClass){if(!(CButton的这个实例))返回新的CButton(buttonName,functionName);this.btn=doc.createElement(“button”);this.btn.setAttribute(“class”,buttonClass);this.btn.setAttribute(“onClick”,functionName);this.btn.innerHTML=buttonName;}
还有其他问题,我无法为返回其他类型(this=doc.createElement(“按钮”))重新定义
this
。如果我使用
返回这个.btn
,使用类没有任何意义,它变成了没有方法的简单函数。为此,请实现您自己的类型,不要重写dom(由于安全漏洞,dom充满了限制)很抱歉我的noob的问题,但我真的无法理解这一点。例如,
appendChild
仅使用HTMLElement类,对吗?如果我创建了自己的类,它就不工作了,因为类应该具有相同的类型。我认为重新定义标准c-tor将是一个好主意。