-1

A bit of confusion. Here's the JS code:

(function(){
    var self = this;
    var view = 12;

    self.value = null;

    .... 
});

I understand using var view = 12 creates a local scope for the view variable. But doesn't self.value also create a "local" scope for the value variable? If so, what is the difference or am I missing something?

nanonerd
  • 1,964
  • 6
  • 23
  • 49
  • 1
    `self.value = ...` simply creates a **property** on the object `self` (`this`) is referring to. Variables and properties are two different beasts. Not sure what you want to compare here. – Felix Kling Dec 02 '14 at 18:20
  • Thanks Felix, I am a newb to JS. After reading your answer, PHeonix's below, and the link provided, I understand the diff. Got it ! – nanonerd Dec 02 '14 at 18:35
  • Functions can be used as constructors. this.something is an instance specific member and members on the constructor prototype are shared among instances. Members declared as var could be available in closures to simulate private members. All explained here: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Dec 03 '14 at 00:48

1 Answers1

1

self is a local variable. With self.value, you're adding a prototypical property on to the self variable and assigning it to null.

Codeman
  • 12,157
  • 10
  • 53
  • 91
  • 1
    What is a "prototypical property"? How would it be different from a "normal" property? – Bergi Dec 02 '14 at 18:30
  • And what is "prototyped variable scope"? *"the basic concept is that you can only access variables in the same scope or a higher scope"* That's how scope works. That has nothing to do with prototypes. – Felix Kling Dec 02 '14 at 18:36
  • @FelixKling OP seems to not understand how scoping works in the first place - that's why I included that tidbit. – Codeman Dec 02 '14 at 18:40
  • @Bergi just emphasizing that JS is a prototypical language - if you're using to working in Java or C#, it's natural that you'd be confused that you can just hang any old thing you want off of an object :) – Codeman Dec 02 '14 at 18:41
  • But you seem to conflate this with prototype inheritance (somehow), which has nothing to do with the code the OP has and is more confusing than helping IMO. Scope has nothing to do with prototypes. – Felix Kling Dec 02 '14 at 18:41
  • @FelixKling ok. I removed it, if you think it's harmful – Codeman Dec 02 '14 at 18:42