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

后端 未结 4 1236
挽巷
挽巷 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:43

    It is as Sean says: you aren't actually creating a new reference to an object (creating a this context), because you are simply calling the constructor - not utilizing the constructor to create a new object. If you use the new keyword, it works just peachy.

    Since the scope of test() is window when you call it, any function called from within test() will execute in the window scope.

    By using the new keyword, you are allocating a new object to memory - and creating a new scope.

    For example, try this in firebug:

    var myFunction = function() {
        this.memberVariable = "foo";
        console.log(this);
    }
    myFunction();
    console.log(window.memberVariable);
    var myObject = new myFunction();
    console.log(myObject.memberVariable);
    

    You will see this result:

    Window stats
    foo
    Object { memberVariable="foo"}
    foo
    

    The Function base object has a method, call(), which as outlined by Craig, allows you to explicitly specify which scope the function should run in:

    var myFunction = function() {
        this.memberVariable = "foo";
    }
    myFunction.call(myFunction);
    console.log(myFunction); // "Function()"
    console.log(myFunction.memberVariable); // "foo"
    

    This is, however, not the preferred way of doing things, as you aren't actually creating a new object here, and typeof myFunction will still return "function" instead of "object" - when you really just wanted to create an object.

提交回复
热议问题