0

I used to write a lot of Javascript, and now I'm just jumping back into it, but it seems like I have lost my mind. I'm trying to create an object using function, and I am doing it just the same way that my online searches suggest I should do. I created this example to show the many ways I have tried.

<script>
function a(){
    function b(){};
    this.c = function(){};
    this.d = 0;
    var e = function(){};
    var f = 0;
}
a.g = function(){};
a.prototype.h = function(){};

var a2 = function(){
    function b(){};
    this.c = function(){};
    this.d = 0;
    var e = function(){};
    var f = 0;
}
a2.g = function(){};
a2.prototype.h = function(){};
</script> 

From what I remember, I should be able to call a.b(), a.c(), and a.d, and likewise for a2.

However, when I try to call them, it doesn't work. When I type the variable name in the console, it doesn't even show them as being an option. I can however call a.g(). I can't call a.h(), but I can call a.prototype.h().

I tried this in chrome, and a few things as well in both firefox and Safari.

As far as I can tell from online tutorials, this is not interacting the way I should be expecting it to.

1 Answer 1

2

b, e and f are variables in the scope of the function a. They are never exposed outside that function.

c and d are assigned, when a is called, to whatever this is. If you call new a() then it will be the instance of a that is returned.

g is a property of a directly, so you can call it.

h is on the prototype chain so it will appear, like c and d, on instances of a created with new.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, thanks. I guess I was missing the 'new' keyword. Makes sense now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.