JavaScript losing “this” object reference with private/public properties

后端 未结 4 1186
挽巷
挽巷 2021-01-27 12:50

I have the following error when running the page below:

\"this.testpublic is not a function\"


test = function() {
        var testprivate = function() {         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-27 13:21

    The problem is that this actually never was referring to the test object to begin with. It was always referring to the nearest enclosing object -- which in this case is window.

    test = function() {
            var testprivate = function(say) {
                    console.log('test', say);
            }
    
            this.testpublic = function(say) {
                    testprivate('test', say);
            }
    
            testprivate();
    }
    x = new test();
    

    This works because, as I understand it, this is determined at call time -- and it is locked into the nearest "enclosing" object*, unless call() or apply() is used.

    * There is probably a much better word for this, but I don't know it off the top of my head. If someone knows, please enlighten us all :-)

提交回复
热议问题