Search code examples
javascriptinheritancereferenceextend

JavaScript referencing an object in an argument


Does JavaScript reference a global object anywhere in the code (function, object, etc)?

I have wrote this and it works as it works (written in inline-comments):

function Extender(object, property, value) {
    object[property] = value;
}

var MyObject = {};

MyObject.zlatan = 'at stackoverflow';

console.log(MyObject.zlatan); // at stackoverflow

// -----

Extender(MyObject, "stackoverflow", function() {
    return console.log('I am executing MyObject.stackoverflow()');
});

MyObject.stackoverflow(); // I am executing MyObject.stackoverflow()

Extender function, as you see, takes three arguments, and with it I can add new properties and their values (strings, numerics, arrays, objects, function callbacks, etc).

One of my questions here is also why don't we need any special pointer/identifier for a referencing variable, like we do in PHP:

$something &= $somethingElse;

or in a PHP function/method:

function something( &$argument ) {
    // etc
}

Solution

  • All variables in JavaScript are references.