Wednesday 23 November 2016

Javascript: dabble in 'new'

The code snippet below demonstates the difference between invoking a function with and without new.
function foo(a) {
    this.a = a;
}

var bar = new foo( 2 );
var bar2 = foo( 2 );

console.log( bar); // foo {a: 2}
console.log( bar.a); // 2
console.log( bar2); // undefined 
console.log( bar2.a); // TypeError
Why bar2 is undefined? Because there is no return statement in foo(). What if there is?
function foo(a) {
    this.a = a;
    return this;
}

var bar = new foo( 2 );
var bar2 = foo( 2 );

console.log( bar); // foo {a: 2}
console.log( bar.a); // 2
console.log( bar2); // Window {top: Window, location: Location, document: document, window: Window, external: Object…}
console.log( bar2.a); // 2
Why bar2.a = 2 while bar2 itself is the Window object? Because this refers to the Window object and this.a essentially creates an 'a' variable in global scope (Window object). Now what if returning something other than this?
function foo(a) {
    this.a = a;
    return 3;
}

var bar = new foo( 2 );
var bar2 = foo( 2 );

console.log( bar); // foo {a: 2}
console.log( bar.a); // 2
console.log( bar2); // 3
console.log( bar2.a); // undefined
Oh, it turns out that having a 'new' precede a function ignores the return statement all together. Although the author of stresses that 'new' in Javascript has nothing to do with the constructor concept in class-oriented languages, I, with a Java background, am still inclined to interpret it as:
class foo{
    var a;
 
    public foo(a){
        this.a = a;
    }
}

var bar = new foo(2);