How to convert an “object” into a function in JavaScript?

前端 未结 8 492
Happy的楠姐
Happy的楠姐 2020-12-01 08:53

JavaScript allows functions to be treated as objects--if you first define a variable as a function, you can subsequently add properties to that function. How do you do the

8条回答
  •  抹茶落季
    2020-12-01 09:38

    var bar = { 
        baz: "qqqq",
        runFunc: function() {
            return 1;
        }
    };
    
    alert(bar.baz); // should produce qqqq
    alert(bar.runFunc()); // should produce 1
    

    I think you're looking for this.

    can also be written like this:

    function Bar() {
        this.baz = "qqqq";
        this.runFunc = function() {
            return 1;
        }
    }
    
    nBar = new Bar(); 
    
    alert(nBar.baz); // should produce qqqq
    alert(nBar.runFunc()); // should produce 1
    

提交回复
热议问题