Can a JavaScript object have a prototype chain, but also be a function?

后端 未结 6 1982
失恋的感觉
失恋的感觉 2020-11-27 19:20
function a () {
    return \"foo\";
}

a.b = function () {
    return \"bar\";
}

function c () { };
c.prototype = a;

var d = new c();
d.b(); // returns \"bar\"
d()         


        
6条回答
  •  自闭症患者
    2020-11-27 19:48

    Based on a discussion on meta about a similar question I'm posting this answer here based on @alexander-mills original


    This can now be done in a standards compliant way

    First create an object which inherits Function

    const obj = Object.create(Function.prototype);  // Ensures availability of call, apply ext
    

    Then add you custom methods and properties to obj

    Next declare the function

    const f = function(){
        // Hello, World!
    };
    

    And set obj as the prototype of f

    Object.setPrototypeOf(f,obj);
    

    Demonstraction

    const obj = Object.create(Function.prototype);
    
    // Define an 'answer' method on 'obj'
    obj.answer = function() {
      // Call this object
      this.call(); // Logs 'Hello, World'
      console.log('The ultimate answer is 42');
    }
    
    const f = function() {
      // Standard example
      console.log('Hello, World');
    };
    
    Object.setPrototypeOf(f, obj);
    
    // 'f' is now an object with an 'answer' method
    f.answer();
    // But is still a callable function
    f();

提交回复
热议问题