[Javascript]Reference/pointer/value?

camelCase

The Case of the Mysterious Camel.
Reaction score
362
When you pass a variable to a function in Javacript, how do you know whether you're passing by value or reference?
Is there a way to control whether you're passing something by reference, pointer or value?

[EDIT]
Also, an unrelated question:
Does Javascript have any class support?
If it does, does it support inheritance?

Like,
Code:
class myClass : public someElement {
    public:
        myClass (int i=0) : myInt(i) {}
        ~myClass () {}
    protected:
        int myInt;
};

Just asking for no particular reason.
I've never *really* found a need for all this, I just wanted to know.
And I never think about references and values when using Javascript, I just debug and fix things if anything goes wrong.
 

UndeadDragon

Super Moderator
Reaction score
448
A couple of articles on OOP in JavaScript and Inheritance in particular.

As for the first part, I haven't looked into JavaScript far enough to be any help there :)
 

JerseyFoo

1/g = g-1
Reaction score
40
PHP:
function Classs(){
    var private = 'derp';

    function privateFunc(){
        return private;
    }

    this.public = 0;

    this.privileged = function(){
        return private;
    }
}
Classs.prototype.public = function(){
    return this.public;
}

var obj = new Classs();

When you pass a variable to a function in Javacript, how do you know whether you're passing by value or reference?
You are always passing by 'reference'. Everything is an object. http://www.w3schools.com/jsref/jsref_valueof_number.asp

Is there a way to control whether you're passing something by reference, pointer or value?
No.

If it does, does it support inheritance?
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Inheritance

Does Javascript have any class support?
Kinda. JavaScript is a prototyping language, there's no need for 'class support'.
 

Magentix

if (OP.statement == false) postCount++;
Reaction score
107
You are always passing by 'reference'. Everything is an object. http://www.w3schools.com/jsref/jsref_valueof_number.asp

This is false. JavaScript (or ECMAScript) has Primitive Types and Reference Types.

As for private properties or methods: they are supported in ECMAScript 5 but, for now, all you can do is simulate them.
The reason I say simulate, is because the private/protected/public bits get complicated as soon as you need class inheritance.

In Professional JavaScript for Web Developers (2nd Edition) by Nicholas C. Zakas, you'll find a whole chapter dedicated to class inheritance in JavaScript.

You can create a 'class' in 3 ways:
var myInstance = new Object();
var myInstance = new SomeCustomFunction();
var myInstance = {};
 

Darthfett

Aerospace/Cybersecurity Software Engineer
Reaction score
615
Reading books is a terrible way to master a language; you only get bad information in the perspective of a bad programmer.

Not true, they can be a great resource for learning, and the personal bias is not present in all books.

This isn't Java, everything in JavaScript is an object. Except null & undefined.

You are always passing by 'reference'. Everything is an object. http://www.w3schools.com/jsref/jsref_valueof_number.asp

All objects are references, but simply because something is a reference, doesn't mean that passing it around is called "passing by reference". I'm pretty sure JavaScript is a pass-by-value language:
Code:
function foo(bar) {
    bar = 8;
}
var spam = 5;
foo(spam);
//spam is still 5.

This works for class objects too.

In a language like C++, you can pass it either way, using a pointer, or the value itself.
 

Magentix

if (OP.statement == false) postCount++;
Reaction score
107
Reading books is a terrible way to master a language; you only get bad information in the perspective of a bad programmer.

This isn't Java, everything in JavaScript is an object. Except null & undefined.

First of all: the book I referred to is considered to be the JavaScript bible by many professionals.
Secondly: Not everything in JavaScript is an object.

Just because you can call a method on an integer (for example), doesn't mean it's an object.

All it means is that ECMAScript is smart enough to:
- know that you are trying to use a method on a non-object (primitive value)
- temporarily convert said primitive value into a reference type
- call said method on the temporary reference type
- return the method's result
- destroy the temporary reference type

There are five primitive values in JavaScript that are stored directly in the stack: Null, Undefined, Boolean, String and Number
If you inspect the memory used by JavaScript, you'll clearly see the difference between primitive values and reference types.

Finally:
You do not pass by reference in JavaScript. Not ever. You always pass a value from the stack.
If the value happens to be a pointer, then it may appear as if you were passing by reference, but in reality you aren't.
ECMAScript is simply not able to pass by reference.
 

GetTriggerUnit-

DogEntrepreneur
Reaction score
129
Not true, they can be a great resource for learning, and the personal bias is not present in all books.





All objects are references, but simply because something is a reference, doesn't mean that passing it around is called "passing by reference". I'm pretty sure JavaScript is a pass-by-value language:
Code:
function foo(bar) {
    bar = 8;
}
var spam = 5;
foo(spam);
//spam is still 5.

This works for class objects too.

In a language like C++, you can pass it either way, using a pointer, or the value itself.

Absolutely, the only way to pass a number by reference is using a parent object,
Code:
var x = { mynumber: 3 }; 
function y(x) { x.mynumber=4 }
y(x);
console.log(x.mynumber) // 4
 

camelCase

The Case of the Mysterious Camel.
Reaction score
362
Oh, my-
I see I've stepped into a huge topic O_O

Thanks for the answers, guys.
Now for the heavy reading ><
 

Lyerae

I keep popping up on this site from time to time.
Reaction score
105
Classes do not exist in JavaScript, and you shouldn't really need them, but in the event you do, just use an object literal:

Code:
var myObject = { 
	myVar: "Hello, world!",
	publicMethod: function() { console.log(this.myVar); }
};

And if you need private variables (not pseudo-private):

Code:
(function() { 
	var myPrivateVar = "Hello, ";
	var myObject = { 
		myVar: "world!",
		publicMethod: function() { console.log(myPrivateVar + this.myVar); }
	};

	window.myObject = myObject; // Expose our object to the global namespace.
})();

@JerseyFoo, you need to read this. Now.

And finally, when in doubt, always check Google, and the MDN. They have information on just about everything.
 

camelCase

The Case of the Mysterious Camel.
Reaction score
362
Oh, damn.
I started (Like, three years ago) HTML, CSS, Javascript, PHP and MySQL from w3schools O_O

I thought they explained everything nicely to me ><

And everything I learned there seems to work fine for me.. =x
Of course, over time, I did use the net often and some of the stuff w3schools taught wrongly was corrected but I think I still do stuff wrongly at times =P
 

Lyerae

I keep popping up on this site from time to time.
Reaction score
105
Yes, w3schools is one of the worst places to learn just about anything. I wouldn't even use them for references. Mozilla has much better documentation on everything, and if that fails, there is always IRC and Google (if you can find some way to get results unrelated to jQuery, that is).
 

GetTriggerUnit-

DogEntrepreneur
Reaction score
129
Yes, w3schools is one of the worst places to learn just about anything. I wouldn't even use them for references. Mozilla has much better documentation on everything, and if that fails, there is always IRC and Google (if you can find some way to get results unrelated to jQuery, that is).
Dis man speaks the truth.
 

JerseyFoo

1/g = g-1
Reaction score
40
Oh, damn.
I started (Like, three years ago) HTML, CSS, Javascript, PHP and MySQL from w3schools O_O

I thought they explained everything nicely to me ><

Don't listen to any of this hosh posh. http://w3fools.com is clearly written by a butthurt microsoft fanboy. Anything not about ASP is just out-of-context nitpicking, much of it has been redacted, and hardly any of it has any warrant. w3schools has been golden since 1999 as a great place to begin web dev and you shouldn't let any idiot try to turn it into this; http://en.wikipedia.org/wiki/Acceleration#Average_and_instantaneous_acceleration

Honestly, did you even read this page? Or did you fall for the copypasta design?


Wrong. In HTML5 the <dl> element represents an association list or description list. This is a much wider meaning than HTML4’s “definition list”. The example is also terrible, even for a definition — here’s hoping w3schools doesn’t start a dictionary side project.
Because w3schools said the definition list element defines a definition list.

Playing a sound after each occurrence of an H1 element is not likely to be a real-world problem that needs solving, nor is it even possible with the current implementation. A better example might include something like:
Criticizing an example because it shows how to play a sound instead of appending "..."; these geniuses sure know how to inspire creativity.

ASP Classic was discontinued in 2000 and replaced with C#/ASP.NET. Recommending people learn an outdated language is not a good next step.
Because they said "ASP or PHP" and not "ASP.NET or PHP".

w3fools.com is a troll; sheepdom ftw. Additionally; although Mozilla has nice tutorials -- they're quickly becoming the biggest joke on the internets, losing market share like a flying penguin on fire loses altitude, blatantly lying about their browser's performance, and showing the world that community-based open source obviously isn't the way.
 

Lyerae

I keep popping up on this site from time to time.
Reaction score
105
I've never found the documentation from Mozilla to be false, whereas the w3schools documentation has been wrong several times.

And w3fools was written by Paul Irish.
 

JerseyFoo

1/g = g-1
Reaction score
40
You can't compare a tutorial to documentation. Like criticizing "A Beginner's Guide To HTML" because it's not as detailed or defined as "Web Development; The Complete Encyclopedia and History". The goal of a writer is to convey & express the most information & understanding with the least effort. Dwelling on technicalities that would only help on a college quiz (maybe) is for trolls.
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top