簡體   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