0

If I wrote some code like below, when I have some functions and I want to wrap them in an object constructor.

As you can imagine, the third console.log shows false, and I can't think of a way to access the object constructor arguments within deeply.

Is there a way to do this or I have to give up using object constructor?

function Obj(a, b){
    this.a = a;
    this.b = b;
    console.log(this.a == a);
    this.fn = function() {
        console.log(this.a == a);
        function fn2() {
            console.log(this.a == a);
            // ...
        }
    fn2();
    };
}

var Obj2 = new Obj(0, 1);
Obj2.fn();
David
  • 77
  • 7
  • The problem isn't accessing the parameter, it's accessing the property; you're not accessing the property because `this` doesn't have the value you expect inside your call to `fn2`. When you call `fn2()` the way you have, you're not doing anything to set `this`, and so it defaults (in loose mode [above], the default is the global object; in strict mode, it would be `undefined`). See the linked question's answers for details. – T.J. Crowder Jan 12 '18 at 11:07
  • Thanks for advising. It seems I'd asked a redundant question. Look through what you suggest, I think I should create a variable copying this to avoid scope issues. @T.J. Crowder – David Jan 12 '18 at 11:18
  • That's one of your options. You have several. (It's not really about "scope," just `this`. They're only slightly related.) – T.J. Crowder Jan 12 '18 at 12:34

0 Answers0