-1

I just learned OOP and there is one little thing that I am not able to solve. The problem is a scope issue of some sort.

If I create a new object then how will I be able to give it access to my constructor function if the constructor function is inside another function? Right now I get undefined. Storing the function in a global variable wont do the job.

  var example = new something x(parameter);
    example.i();

    var getFunction;

    var onResize = function() {

        getFunction = function something(parameter) {
            this.i= (function parameter() {
                    // Does something
            });
        };
    };

window.addEventListener('resize', onResize);
onResize();
Asperger
  • 3,064
  • 8
  • 52
  • 100
  • 4
    You are using the words "constructor", "method", "parent" and "connection" haphazardly, to the point where it's almost impossible to even begin to guess what you mean. Also, your code has a syntax error on the very first line and the second is already really weird. Please, take some time to explain yourself better. – jrsala Sep 18 '15 at 22:22
  • @jrsala edited my post. Does this explain it better? – Asperger Sep 18 '15 at 22:30
  • 3
    I see what you mean but you have to learn to express yourself better because what you're saying is still nonsensical. At any rate, you cannot `new` a constructor function before that function is defined, so what you can do instead is wait until it does get defined in order to create your object with it, inside `onResize`. And please, fix the syntax errors in your code. – jrsala Sep 18 '15 at 22:34
  • @jrsala fixed the example code. I am eager to understand why my new question is not well formulated. Please let me know so that those mistakes dont happen again. – Asperger Sep 18 '15 at 22:41
  • You did not fix the example code. `new something x(parameter);` is not valid JavaScript, it won't run anywhere. It's good that you removed the `new` from `new example.i()` though because a statement that consists solely of a construction with `new` should never occur. If you could explain to us the exact problem that you are trying to solve, we could answer in terms less general and more useful for you. – jrsala Sep 18 '15 at 23:02

2 Answers2

0

For OOP javascript, the pattern should be like this.

//defining your 'class', class in quotes since everything is just functions, objects, primitives, and the special null values in JS
var Foo = function (options) {
  // code in here will be ran when you call 'new', think of this as the constructor.

  //private function
  var doSomething = function () {
  }

  //public function
  this.doSomethingElse = function () {
  }
};

//actual instantiation of your object, the 'new' keyword runs the function and essentially returns 'this' within the function at the end
var foo = new Foo(
    {
      //options here
    }
)
teaflavored
  • 440
  • 4
  • 9
  • Does it have to be top to bottom? I actually require it the other way around. I know some libraries manage to do this in some way. – Asperger Sep 18 '15 at 22:44
  • javascript variables always get hoisted to the top of the scope, but that doesn't mean that they are defined. At the time when you want to run 'new Foo()', Foo must be defined. EDIT I shouldn't say always since different JS environments may behave differently – teaflavored Sep 18 '15 at 22:49
  • @teaflavored gwg is right, Foo does **not** have to be defined in the code before it is `new`ed if it is not immediately assigned to a variable. – jrsala Sep 18 '15 at 22:58
  • @jrsala could you elaborate? new keyword is reserved for functions, if Foo is not defined ( not a function ) , then how could you call new on it. – teaflavored Sep 18 '15 at 23:15
  • @teaflavored See gwg's link. Function definitions of the form `function f() {/* */}` without an immediate assignment (no `var func = function f() {/* */}`) are hoisted too. You can write the following, and it will be valid: `var obj = new Foo(); function Foo() { this.x = 2; }` – jrsala Sep 18 '15 at 23:23
  • oh yes, I mean i know that. In that case Foo is hoisted to the top, so it is defined at the time of running obj. – teaflavored Sep 18 '15 at 23:25
0

If I understand you, you want to know how to access variables inside another function. Your attempt is reasonable, but note that getFunction is not bound until after onResize is called. Here's a bit of a cleaner demo:

var x;

function y() {

    // The value is not bound until y is called.
    x = function(z) {
        console.log(z);
    }
}

y();
x('hello');

A common JavaScript pattern is to return an object that represents the API of a function. For example:

function Y() {
    var x = function(z) {
        console.log(z);
    }

    return {
        x: x
    };
}

var y = Y();
y.x('hello');

You should definitely read up on the basic concepts of JavaScript. Your code and terminology are both sloppy. I'd recommend Secrets of the JavaScript Ninja. It does a good job explaining scope and functions, two tricky topics in JavaScript.

jds
  • 7,910
  • 11
  • 63
  • 101
  • Im capable of building plugins already but it seems I mix up terminology which greatly reduces my capability to communicate with other developers. I dont know why this happens. It bothers me somehow. Maybe because im new to OOP. – Asperger Sep 18 '15 at 22:48
  • Mixing up terminology => mixing up concepts. Communication is part of it, but appreciate that it might be a bigger issue. – jds Sep 18 '15 at 22:52
  • 1
    you are absolutely right. The book you just showed me is really great. I will buy this today – Asperger Sep 18 '15 at 22:54
  • Hang on, I could always do window.addEventListener('resize', onResize); onResize(); – Asperger Sep 18 '15 at 22:56
  • Resize is called when page is loaded. So it should be defined by then. – Asperger Sep 18 '15 at 22:57
  • Can you update your question to have these details, then? Because my example definitely works. – jds Sep 18 '15 at 22:57
  • Okay, but what you're doing is equivalent to calling `x('hello')` at the beginning of the program and `y();` at the end. Do you see why this is wrong? The event listener is irrelevant in this case—we don't know if it will ever be called. – jds Sep 18 '15 at 23:02
  • Absolutely. This is an issue. I know some libraries let you create new objects before the script. So basically instead of top down, bottom up. Im sure the functions there are nested like hell. I know how to return arrays, variables but an entire function ... – Asperger Sep 18 '15 at 23:08
  • You're talking about function declarations, which load before code is executed: stackoverflow.com/a/3344397/1830334. All that changes is that `y` will be in scope sooner in the lifetime of the program. But that does not change the fact that `x` is `undefined` until `y` is *called*. It has nothing to do with the type of the variable assigned to `x` (array vs function). – jds Sep 18 '15 at 23:36
  • Is this what we call a closures problem? – Asperger Sep 18 '15 at 23:45
  • Not per se. It has more to do with how the program is interpreted and executed. – jds Sep 19 '15 at 15:01