You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

尝试给函数原型绑定mytest方法时出现Uncaught TypeError错误的技术咨询

Hey there! Let's break down why you're seeing that TypeError and walk through how to fix it.

Error Cause Analysis

First off, the a variable you defined is an arrow function. A key trait of arrow functions is that they do NOT have their own prototype property. When you try to access a.prototype, you get undefined—hence the error when you try to assign mytest to it.

On top of that, even if a did have a prototype, calling a("div") returns the result of document.querySelector(e)—a DOM element (like an HTMLDivElement instance). This element's prototype chain has nothing to do with a's prototype, so adding methods to a.prototype wouldn't make them available to the DOM element anyway.

Fixes

Based on what you're trying to do, here are two solid solutions:

Solution 1: Add the method to the DOM Element prototype

If you want all DOM elements to be able to call mytest, you can extend the Element prototype directly:

(function() {
  window.onload = function() {
    Element.prototype.mytest = function(e) {
      // Add your method logic here, e.g.:
      console.log(`Called mytest with parameter: ${e}`);
      console.log(`Target element:`, this);
    };
    
    // Now any DOM element can use this method
    document.querySelector("div").mytest("d");
  };
})();

⚠️ Heads up: Modifying native prototypes is convenient but can cause naming conflicts with other code. Use this approach carefully.

Solution 2: Wrap the DOM element in a custom object

If you don't want to pollute native prototypes, wrap the DOM element in an object that includes your custom method:

(function() {
  window.onload = function() {
    function a(selector) {
      const element = document.querySelector(selector);
      // Return an object with the DOM element and your custom method
      return {
        element,
        mytest(e) {
          // Your method logic here—use this.element to access the DOM node
          console.log(`Called mytest with parameter: ${e}`);
          console.log(`Target element:`, this.element);
        }
      };
    }
    
    // Usage stays the same as your original code
    a("div").mytest("d");
  };
})();

This approach keeps your custom logic isolated without messing with native browser prototypes, making it safer for larger projects.

Quick Side Note: Why arrow functions lack prototypes

Arrow functions are designed to be lightweight shorthand functions. They don't have their own this, prototype, or arguments object—they inherit these from the surrounding scope. So if you need a function with a prototype, you have to use a regular function declaration or expression.


内容的提问来源于stack exchange,提问作者gabrielubs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 09:47:27