0
function Person(name, family) {
    this.name = name;
    this.family = family;
}

Person.prototype.getFull = function() {
    return this.name + " " + this.family;
};

Why do we have to put this.name = name; this.family = family;? Why this.? Why can't we just do var name1 = name?

  • Object properties are not the same thing as variables. – Barmar Sep 18 '15 at 22:47
  • Because `var p = new Person('bob', 'smith');` will set `p` to (refer to) this object: `{name:'bob', family:'smith'}`. If you do `var name=name`, then `p` will refer to an empty object `{}` because you have not set any instance properties on it. By the way, this question is probably replicated umpteen times all over SO and elsewhere. – caasjj Sep 18 '15 at 22:52
  • @Barmer so general even i know that. doesn't ans question –  Sep 19 '15 at 04:46

2 Answers2

2

var creates a local variable that is ONLY available within the scope of the function it is declared in (the constructor in the case of your question).

this.name = xxx assigns a property to the current object that was just created in the constructor and would be available to anyone who has a reference to that object.

Within the object constructor when it is called with the new operator, this is set to a newly created object of the type defined in the constructor and its prototype. So, to reference properties on that instance of the object, you MUST use this.xxx.

So, you must use whichever of the two techniques matches what you are trying to do. There are cases for local variables in the constructor with var and there are cases to initialize instance variables.

Here's an example of the difference:

Instance variable:

function Person(name, family) {
    this.name = name;
    this.family = family;
}

Person.prototype.getFull = function() {
    return this.name + " " + this.family;
};

var p = new Person("Bob", "Smith");
console.log(p.name);    // "Bob"

Local Variable:

function Person(name, family) {
    var aName = name;
    var aFamily = family;
    // these variables are local and only available 
    // within the scope of the constructor
}

Person.prototype.getFull = function() {
    // this.name and this.family are not defined
    return this.name + " " + this.family;
};

var p = new Person("Bob", "Smith");
console.log(p.aName);    // undefined
console.log(p.aFamily);   // undefined

Extra Credit: Private Instance Variables

There is a hybrid model where you define methods within the constructor and those methods ONLY can then access the local variables within the constructor. Those variables then behave like "private" instance variables. They are not technically properties of the object, but are available to any methods defined within the constructor because of the closure created. It's a neat trick for private instance variables. Here's an example:

function Person(name, family) {
    var aName = name;
    var aFamily = family;

    // define method within the constructor that has access to
    // local variables here
    this.getFull = function() {
        return aName + " " + aFamily;
    }
}

var p = new Person("Bob", "Smith");
console.log(p.getFull());    // "Bob Smith"
console.log(p.aName);        // undefined, not instance properties
console.log(p.aFamily);      // undefined, not instance properties
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • what is the right SO guidelines on answering (as opposed to just commenting) on what is clearly a duplicate question? – caasjj Sep 18 '15 at 22:54
  • @caasjj - If you know of a good duplicate that perfectly answers the question, then vote to close the OP's question as a duplicate. I wasn't aware of such a duplicate so I answered the question. Answers should not be provided in comments. – jfriend00 Sep 18 '15 at 22:55
  • thx for the guideline, but I don't think I have the rep to vote for duplicate (?), but searching 'stackoverflow var vs this' in google or duckduckgo turns up stackoverflow.com/questions/4354418/…, and stackoverflow.com/questions/27589494/javascript-var-vs-this, and .., – caasjj Sep 18 '15 at 23:14
  • @caasjj - Then, until you have the reputation to vote to close ([which looks like it requires 3000 points](http://stackoverflow.com/help/privileges)), you can comment on the original question with a link to recommended duplicates and others who have enough rep will see if they agree with you. – jfriend00 Sep 18 '15 at 23:18
  • @sdfdsfsdf - that is a much discussed question. Here are some references: [Advantages of using prototype, vs defining methods straight in the constructor?](http://stackoverflow.com/questions/4508313/advantages-of-using-prototype-vs-defining-methods-straight-in-the-constructor/4508498#4508498), [Use of Prototype vs. this in Javascript](http://stackoverflow.com/a/310927/816620) and there are many more similar answers. – jfriend00 Sep 19 '15 at 06:18
  • @sdfdsfsdf - I'm sorry, I don't understand either of the things you're asking about in your latest comment. Since it appears this may be beyond the scope of your original question - perhaps you should accept an answer to your current question if you feel it was answered (click green checkmark to the left of an answer) and then post a new question where you can more fully explain what you are asking. – jfriend00 Sep 19 '15 at 20:54
  • @sdfdsfsdf - yes, anything can be assigned to that property. It's just a property on an object, no different than any other property on any other object in Javascript. – jfriend00 Sep 19 '15 at 21:03
  • @sdfdsfsdf - the constructor is for initializing instance variables. If you don't have any instance variables, then perhaps you don't actually need an instance of an object at all since instance variables are the main point of having a dynamically created object. You can have a blank constructor, though it is not common. – jfriend00 Sep 19 '15 at 21:16
  • @sdfdsfsdf - you would really benefit from a good tutorial or lesson on object oriented programming in Javascript. I'd suggest you do some Google searches and some reading or find a good book. Yes, you can change a property from outside the object. Please refrain from using the comment system here at StackOverflow as a running Q&A stream. That is not how this site is meant to be used. If you have more questions that you've done basic research and learning on and are still confused, then you should ask a new question here on StackOverflow. – jfriend00 Sep 19 '15 at 21:35
0

You could do var name1 = name. But then this variable would be a private variable inside the person scope and your prototypes or anything outside the person scope would not be able to directly access them without a property inside the parent function which acted as a get function which returned that var.

We use the object properties so that they can be shared or accessible outside the parent scope.

ChoclateLove
  • 672
  • 1
  • 6
  • 11
  • Now tell me 1 thing. Why should I use prototype? I heard it is more efficient in the memory? Explain in simple terms please –  Sep 19 '15 at 04:43
  • Yeah you are correct about it being more memory efficient. Because lets say we define all our methods as properties in our object, every time we instantiate that object we recreate all the properties for each new object. Where as if we defined all our methods on the prototype, they would not be recreated every time. Also on the client browsers prefer to look up based on prototypes – ChoclateLove Sep 19 '15 at 08:03