javascript add prototype method to all functions?

前端 未结 4 890
星月不相逢
星月不相逢 2021-02-05 09:54

Is there a way to add a method to all javascript functions without using the prototype library?

something along the lines of :

Function.prototype.methodN         


        
相关标签:
4条回答
  • 2021-02-05 10:24

    Try Object.prototype instead:

    Object.prototype.methodName = function(){ 
    
      return dowhateverto(this) 
    };
    

    But also heed the warning that extending native objects is not always a good idea.

    Function.prototype can't really be manipulated reliably in Javascript; it isn't a real object, because Function() constructor needs to return a function, not an object. But, you can't treat it like a normal function either. Its behaviour when you try to access its 'properties' may be undefined and vary between browsers. See also this question.

    0 讨论(0)
  • 2021-02-05 10:26

    Changing JS built-in objects can give you some surprises.
    If you add external libraries or changing the version of one of them, you are never sure that they won't overwrite your extension.

    0 讨论(0)
  • 2021-02-05 10:32
    function one(){
        alert(1);
    }
    function two(){
        alert(2);
    }
    
    var myFunctionNames = ["one", "two"];
    
    for(var i=0; i<myFunctionNames.length; i++) {
        // reference the window object, 
        // since the functions 'one' and 'two are in global scope
        Function.prototype[myFunctionNames[i]] = window[myFunctionNames[i]];
    }
    
    
    function foo(){}
    
    foo.two(); // will alert 2
    
    0 讨论(0)
  • 2021-02-05 10:40

    Sure. Functions are objects:

    var foo = function() {};
    
    Function.prototype.bar = function() {
      alert("bar");
    };
    
    foo.bar();
    

    Will alert "bar"

    0 讨论(0)
提交回复
热议问题