简体   繁体   中英

How to redefine constructor of standard function in JS?

So, I want redefine constructor of HTMLButtonElement with input args. I know how to do this without 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();

And it's works, but I want use this class something like var myButton = new CButton(arg 1, arg 2, etc); . This method don't let me doing CButtonPrototype.createdCallback = function(arg 1, arg2) . How can I resolve this? Maybe you know another way?

Thanks \\o/

if you need to extend this type, please consider the following:

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

about your original question:

you can't insert parameters because this "function" is only a delegate to a system function... in your case - an object c'tor.

to test it you can try arguments - a special array inside every function in js that represents the arguments of the function:

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

run this code - you will see an empty array - mainly because your c'tor call 'new CButton()' has no arguments. try to insert arguments and you will get an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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