2
function Class () {
var self = this;
this.hi = true; // this { hi: true }, self { hi: true }
self.hi = false; // this { hi: false }, self { hi: false }
}

Why doesn't self behave like a normal var?

asked May 22, 2013 at 13:14
2
  • because they are pointers.. pointing to the same object Commented May 22, 2013 at 13:15
  • 1
    It does act like a normal var. Object reference 101. var x = {}; var y = x; y.z = "1"; alert(x.z); Commented May 22, 2013 at 13:15

2 Answers 2

5

It's because this is (always) an object, not a primitive.

When you assign a variable containing (or more accurately "pointing at") an object to a new variable, both variables point at the same object - it's "copy by reference". Changes to the contents of that object will be visible through both variables.

When you assign a variable containing a primitive to a new variable, you assign a copy of that value to the new variable. Changes to the original variable do not affect the new variable.

answered May 22, 2013 at 13:18
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer, didn't know about this difference.
1

There's nothing special about self here. Try it with any two variable names. This is how most modern languages work.

var x = {};
var y = x;
x.hi = true; // x { hi: true }, y { hi: true }
y.hi = false; // x { hi: false }, y { hi: false 

As Jack pointed out, the key thing to realize here is that both variables are referencing the same object.

Note that if you want to "copy by value" in cases like this (copying objects), you do have options. Some libraries, such as Underscore and Lo-Dash, have a clone method that you can use to create a new object and populate it with all the same properties as another:

var y = _.clone(x);
answered May 22, 2013 at 13:18

2 Comments

there is something special about this - it's an object, not a primitive.
I said there's nothing special about self (by which I mean, the actual word "self"). Obviously you're right that objects are different from so-called "primitives"; but there'd be no opportunity for the OP to get confused by that in this way since you can't mutate primitives to begin with.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.