JavaScript Private Variable

Defining a private variable is a matter of using ‘var’ instead of ‘this’. This is true with every kind of members: variables or functions.

var MyClass = function (param1, param2) {
    this.member1 = param1 || "";    // Public 
    var member2 = param2 || "";     // Private

    // Private 
    var function1 = function () {
        this.member1 = "[" + this.member1 + "]";
        console.log(this.member1);
    };

    // Public 
    this.function2 = function () {
        console.log(member2);
    };
};

var x = new MyClass ("m1","m2");
console.log("Access public member: " + x.member1);
x.function2();

The code above works, but if you try to access “member2” you will get undefined. If you try to access “function1”, you will get an exception that the function doesn’t exist.

In the following, code we introduce prototype function. While there is many advantages like that the function will be shared in memory across all instances. However, one drawback is that you cannot access private members of the class. In the example below, the function4 doesn’t work because it tries to access a member initialized with “var”.

var MyClass = function (param1, param2) {
    this.member1 = param1 || "";    // Public 
    var member2 = param2 || "";     // Private

    // Private 
    var function1 = function () {
        this.member1 = "[" + this.member1 + "]";
        console.log(this.member1);
    };

    // Public 
    this.function2 = function () {
        console.log(member2);
    };
};
MyClass.prototype.function3 = function(){
  console.log("Function 3 Proto : " + this.member1);
};
MyClass.prototype.function4 = function(){
  console.log("Function 4 Proto : " + this.member2);
};

var x = new MyClass ("m1","m2");
x.function3(); // "Function 3 Proto : m1"
x.function4(); // "Function 4 Proto : undefined"

JavaScript Bind and Apply/Call Method

JavaScript has three methods that are useful to assign on what “this” refer to. These three methods are Bind, Apply and Call.

Bind are from the prototype of Function. It takes as first parameter the reference to “this”, and all the subsequent parameters to be the argument to the function. The Bind method return a copy of the function with this one having the “this” to the one desired.

Call is similar, but instead of returning a copy with the provided reference to “this”, it provides the “this” reference and invoke the method.

Apply is like call but the second parameter is an array instead of being a signature with undermined amount of parameter.

Here is an example to distinct the difference:

f1.call(myThisRef, param1, param2, param3);
// or
f1.apply(myThisRef, [param1, param2, param3]);

How can this be useful? This can be useful to change the context of a piece of code to access different member without assigning the values. For example, in the following code we have the same function and by calling apply or bind we can assign “this” to a complete new object that has what is using by “this”, in that case the _name.

var hero = {
    _name: 'John Doe',
    getName: function (){
        return this._name;
    }
};

console.log(hero.getName()); // John Do
// ---
var hero2= {
    _name: 'Patrick'
}
var getNameMethod = hero.getName;

console.log(getNameMethod.apply(hero2));  // Patrick
console.log(getNameMethod.bind(hero2)()); // Patrick

This example illustrates that apply can be called to have momentary a call with a reference to the hero2 instead of the original hero. On the next line, the bind method is called and executed by using the parentheses right away. Normally, we would store the return value of the bind method to get an object that can get subsequent calls with the hero2 “this” reference.

When to use of of the other? apply and call should be used when it’s only for one invocation. Bind should be used to store the new variable with that will have a “this” with the provided reference to “this” when created with bind.

JavaScript Four Patterns to Invoke a Function

There are four ways to call a function in JavaScript. In this article, we will see them all and see the pros and cons of each of them.

Function invocation pattern
This is when a function is not attached to anything, it’s floating which in fact is attached to “window” when in a browser if this one is created not within an object. Here is two examples:

var f1 = function(){console.log("F1")};
f1();
window.f1();
function f2(){console.log("F2");}
f2();
window.f2();

However, if a function is not bound to an object but created withing a function, this one belong to the function. Still, it is not attached to anything.

var myObject = {
  function2 : function(){
    console.log("Function2");
    var function2_1 = function(){
      console.log("Function2_1");
    };
    function2_1();
  }
};
myObject.function2();

Method invocation pattern
Method invocation pattern is when a function is attached to an object that is not instantiated with the “new” keyword.

var myObject = {
  function2 : function(){
    console.log("Function2");
  }
};
myObject.function2();

Constructor invocation pattern
I already covered in previous article about prototype. Invoking with a constructor trigger the prototype chain for the created object. Constructor function are created with the keyword “new”.

var MyClass1 = function() {
  this.function2 = function() {
  return "F2";
  };
};

MyClass1.prototype.function1 = function() {
  return "F1";
};

var instance = new MyClass1();
console.log(instance.function1());
console.log(instance.function2());

As you can see, you can invoke method from the instance or the prototype.

Apply invocation pattern

The last pattern is to use a function to call a function! This is possible because every object has some default function attached to their prototype, like the one that interest us which is “apply”.

The following example shows how to invoke with apply. Both call to the apply function uses the class’ prototype which call the function and apply. The difference is that one pass the method which has a member assigned with “this”, while the second call an anonymous object. The importance is to have a “m1” member because function1 access it in its prototype.

The important detail about “apply” is the parameter. The first one is the pointer “this”, the others are the the function arguments.

var MyClass1 = function() {
  this.m1 = "Member Value";
};

MyClass1.prototype.function1 = function() {
  return "From function1 here is the m1 value : " + this.m1;
};

var instance = new MyClass1();
var objectOnTheFly = {m1:"on-the-fly"};
console.log(MyClass1.prototype.function1.apply(MyClass1()));
console.log(MyClass1.prototype.function1.apply(objectOnTheFly));

In this example, the “this” got assigned dynamically and the function uses the value by accessing with “this”.

In this article we saw 4 different ways to invoke function in JavaScript.

JavaScript Prototype Part 4 : hasOwnProperty

hasOwnProperty is a function from Object’s prototype, hence every thing in JavaScript has access to it. It allows to know if a member is directly having the member specified by string.

Let’s take this simple example where a property “m1” is defined 4 times at each level (child, child prototype, base and base prototype).

var BaseClass1 = function() {
  this.m1 = "m1 base";
};
 
BaseClass1.prototype.m1 = "m1 proto base";
 
var ChildClass1 = function() {
  BaseClass1.call(this); // Call the constructor of the base class
  this.m1 = "m1 child";
};
 
ChildClass1.prototype = Object.create(BaseClass1.prototype);
ChildClass1.prototype.m1 = "m1 child proto"
 
ChildClass1.prototype.constructor = BaseClass1;
var instance1 = new ChildClass1();

console.log(instance1.hasOwnProperty("m1"));

The output is “true”. This is because the instance1 has a property “m1”. If we remove “m1” from the child class, the value will be “true”. The question is, is it true because of the child prototype or the base class? The answer is the base class. Prototype definition wouldn’t be counted has own property. So, the following code return false:

var BaseClass1 = function() {
  //this.m1 = "m1 base";
};
 
BaseClass1.prototype.m1 = "m1 proto base";
 
var ChildClass1 = function() {
  BaseClass1.call(this); // Call the constructor of the base class
  //this.m1 = "m1 child";
};
 
ChildClass1.prototype = Object.create(BaseClass1.prototype);
ChildClass1.prototype.m1 = "m1 child proto";
 
ChildClass1.prototype.constructor = BaseClass1;
var instance1 = new ChildClass1();
console.log("Result " + instance1.hasOwnProperty("m1"));

If we want to use hasOwnProperty on the prototype we will see that it returns false. However, it’s possible to use the method “call” to execute from the base object into an instance, like the following:

var BaseClass1 = function() {
  this.m1 = "m1 base";
};
 
BaseClass1.prototype.m1 = "m1 proto base";
 
var ChildClass1 = function() {
  BaseClass1.call(this); // Call the constructor of the base class
  this.m1 = "m1 child";
};
 
ChildClass1.prototype = Object.create(BaseClass1.prototype);
ChildClass1.prototype.m1 = "m1 child proto";
 
ChildClass1.prototype.constructor = BaseClass1;
var instance1 = new ChildClass1();

console.log("Result 1" + BaseClass1.hasOwnProperty("m1"));
console.log("Result 2" + Object.prototype.hasOwnProperty.call(instance1,"m1"));

This will return false for the first result, and true for the result #2. The first one is false because it’s not using the instance, but the prototype. The second is true because it uses the object and use call which pass the “this” context to be the instance1 which is having m1 (in the child and base).

How can this be useful? Well, it can be useful to determine which member is from the object and which is part of the prototype hierarchy. In the following example, you will see that we will loop through the instance and get members from the child, child prototype, base, base prototype as well as a constructor.

var BaseClass1 = function() {
  this.m2 = "m1 base";
};
 
BaseClass1.prototype.m3 = "m1 proto base";
 
var ChildClass1 = function() {
  BaseClass1.call(this); // Call the constructor of the base class
  this.m4 = "m1 child";
};
 
ChildClass1.prototype = Object.create(BaseClass1.prototype);
ChildClass1.prototype.m1 = "m1 child proto";
 
ChildClass1.prototype.constructor = BaseClass1;
var instance1 = new ChildClass1();

for (name in instance1) {
  console.log(name + ': ' + instance1[name]);
}

The result is:

"m2: m1 base"
"m4: m1 child"
"m1: m1 child proto"
"constructor: function () {
  this.m2 = 'm1 base';
}"
"m3: m1 proto base"

By introducing a condition that use hasOwnProperty we can be sure to just get m2 and m4 (child and base) without prototype.

var BaseClass1 = function() {
  this.m2 = "m1 base";
};
 
BaseClass1.prototype.m3 = "m1 proto base";
 
var ChildClass1 = function() {
  BaseClass1.call(this); // Call the constructor of the base class
  this.m4 = "m1 child";
};
 
ChildClass1.prototype = Object.create(BaseClass1.prototype);
ChildClass1.prototype.m1 = "m1 child proto";
 
ChildClass1.prototype.constructor = BaseClass1;
var instance1 = new ChildClass1();


for (name in instance1) {
  if(instance1.hasOwnProperty(name)){
    console.log(name + ': ' + instance1[name]);
  }
}

Which returns:

"m2: m1 base"
"m4: m1 child"

In this article we saw the power of hasOwnProperty that can help to distinct which members of an object is from the object and inheritance against which members if from the prototype chain.

JavaScript Prototype Part 3 : Constructor with Parameter

Adding a parameter to a constructor in JavaScript is not complicated if you already have your object setup. It’s also not much more work to have some values passed to the base class.

The base class and the child class need to define their arguments they want to allow. To demonstrate, we will have 2 parameters for the child which one of this parameter will be set to the base class.

The main change is to change the function that represent the class by adding a parameter. In the following code, we can see that BaseClass1 class function is now having a function with baseMember has a parameter. We can also see the ChildClass1 to have a function with two. The result is that we can now create with “new” an instance and specifying two parameters.

var BaseClass1 = function(baseMember) {
  this.baseMember = baseMember;
};

var ChildClass1 = function(childMember, baseMember) {
  BaseClass1.call(this, baseMember); // Call the constructor of the base class
  this.childMember = childMember;
};

ChildClass1.prototype = Object.create(BaseClass1.prototype);

ChildClass1.prototype.constructor = BaseClass1;
var instance1 = new ChildClass1("C","B");
console.log("instance1.childMember: "+ instance1.childMember); 
console.log("instance1.baseMember: "+ instance1.baseMember); 

The output will be :

"instance1.childMember: C"
"instance1.baseMember: B"

As you may have realize, since we are using a function to create class in JavaScript, this bring some limitations. The main one is that you can only have a single constructor. It means that if you need to pass different type of information you need to check the type of the object passed or have optional parameter.

Checking the type can be done with typeof to see if it’s a number, string, array or an object. It’s also possible to use instanceof to do logic depending of a specific type of object.

var ChildClass1 = function(childMember, notalwaysprovided) {
  if(typeof childMember === "string"){
    console.log("The name was from a string with the value : " + childMember);
  }else{
    console.log("The name was from an object with the value :" + childMember.name);
  }
  console.log("This parameter is not always provided: " + (notalwaysprovided  || "Default Value"));
};
var instance1 = new ChildClass1("Name1", "second optional param");
var instance2 = new ChildClass1({name:"Name2"});

The output is :

"The name was from a string with the value : Name1"
"This parameter is not always provided: second optional param"
"The name was from an object with the value :Name2"
"This parameter is not always provided: Default Value"

JavaScript Prototype Part 2 : Inheritance (Classical Approach)

In this article, we will see how to create inheritance with JavaScript’s prototype in a classical approach.

We will create a base class and a child class. The base class will have 3 functions on its prototype. We will override one of these functions inside the child class in two different ways. The first one will override by a function attached to the instance, the second one will override the function attached to the prototype.

To have inheritance with JavaScript there is two steps once the class are created.

The first step is to call the base class constructor with the the this parameter. This is done by using the name of the function (the class) followed by “call” with “this” as parameter.

The second step is to set the prototype of the child class to an instance of a new base object. This is done my calling assigning the prototype to Object.Create(.prototype). An important detail is that this must be set before you associate any new prototype to the object, otherwise, every prototype defined will be overridden.

The third step is to set the prototype of the child class to be setup to the childclass. That is that the Object.create set the prototype to the base class which need to set back to the child. We can see that without setting this constructor that the value of console.log(ChildClass1.prototype.constructor) is the base class instead of the child class.

var BaseClass1 = function() {
  this.memberbase = "base";
  this.function4 = function(){
    return "return function4 from base instance";
  };
};

BaseClass1.prototype.function1 = function() {
  return "return function1 from base prototype";
};
BaseClass1.prototype.function2 = function() {
  return "return function2 from base prototype";
};
BaseClass1.prototype.function3 = function() {
  return "return function3 from base prototype";
};

var ChildClass1 = function() {
  BaseClass1.call(this); // Call the constructor of the base class [Step1]
  this.memberclass = "Child";
  this.function2 = function(){
    return "return function2 from child";
  };
};

ChildClass1.prototype = Object.create(BaseClass1.prototype); // [Step2]
ChildClass1.prototype.constructor = ChildClass1; // [Step3]
ChildClass1.prototype.function1 = function() { // Must be after previous line
  return "return from child";
};

var instance1 = new ChildClass1();

console.log("instance1.function1: "+ instance1.function1()); // override with prototype of child
console.log("instance1.function2: "+ instance1.function2()); // override with instance function
console.log("instance1.function3: "+ instance1.function3()); // Use base class function
console.log("instance1.function4: "+ instance1.function4()); // Use base class function
//console.log(ChildClass1.prototype.constructor) // uncomment to see what step 3 change.

The output is :

"instance1.function1: return from child"
"instance1.function2: return function2 from child"
"instance1.function3: return function3 from base prototype"
"instance1.function4: return function4 from base instance"

What we can see is that the chain of priority when calling a function start with the child instance function, move up to the child prototype function, then to the base prototype function. So, it’s possible to redefine a base member in 3 different levels.

The priority will always be : Child instance, Base instance, Child prototype, Base prototype.

We can prove it with this example:

var BaseClass1 = function() {
  this.function1 = function(){
    return "Base Instance";
  };
};

BaseClass1.prototype.function1 = function() {
  return "Base Prototype";
};

var ChildClass1 = function() {
  BaseClass1.call(this); // Call the constructor of the base class
  this.function1 = function(){
    return "Child Instance";
  };
};


ChildClass1.prototype = Object.create(BaseClass1.prototype);
ChildClass1.prototype.function1 = function() { // Must be after previous line
  return "Child Prototype";
};

ChildClass1.prototype.constructor = BaseClass1;
var instance1 = new ChildClass1();
console.log("instance1.function1: "+ instance1.function1()); 

This will print : “instance1.function1: Child Instance”.

If we remove this instance function, this will print : “instance1.function1: Base Instance”

If we remove the base instance function, this will print: “instance1.function1: Child Prototype”

If we remove the base prototype function, this will print:
“instance1.function1: Base Prototype”

In this last example, we were using Object.create, but also new to create the instance that we manipulate the data. If we want to avoid completely the “new”, we need to create the child class with Object.Create. This is possible, but will require to change the child class. For example, we won’t specify function 1 inside ChildClass1 function, neither call BaseClass with call. The code would look like:

var BaseClass1 = function() {
  this.function1 = function(){
    return "Base Instance";
  };
};

BaseClass1.prototype.function1 = function() {
  return "Base Prototype";
};


var ChildClass1 = Object.create(BaseClass1.prototype, {
    name3: { value: "MyName3" },
    function1: {
        value: function () {
            return "Child Instance";
        }
    }
});

ChildClass1.function1 = function() { // Must be after previous line
  return "Child Prototype";
};

var instance1 = Object.create(ChildClass1, {
    memberclass : { value: "Child" }
});

console.log("instance1.function1: "+ instance1.function1()); 

JavaScript Prototype Part 1

JavaScript is a prototype language. Every object has a prototype which share properties between the same kind of object.

The minimal prototype an object has is the default Object.prototype. However, any object can add members or function to its own object prototype by using “.prototype.”. The following code shows that an object type “myTest” with no member is having “member1” dynamically added as well as a member2 with the value “m2”. We create a second instance and only member2, from the prototype is available. The member1 was added to the instance, not the prototype.

var myTest = {};
var myTestInstance1 = Object.create(myTest);
myTestInstance1.member1 = "m1";
myTestInstance1.__proto__.member2 = "m2"

var myTestInstance2 = Object.create(myTest);

console.log("instance1.member2:"+myTestInstance1.member2); //m2
console.log("instance2.member2:"+myTestInstance2.member2); //m2
console.log("instance1.member1:"+myTestInstance2.member1); //m1
console.log("instance2.member1:"+myTestInstance2.member1); //undefined

Prototype inheritance bring method and function. At anytime, it’s possible for the instance to override the prototype member. Here is an example that the prototype is defined in a member to show “m2” and the first instance override it with “Override” string. When a new instance is created, the member will have the value of the prototype.

var myTest = {};
var myTestInstance1 = Object.create(myTest);
myTestInstance1.__proto__.member2 = "m2"
myTestInstance1.member2 = "OVERRIDE";

var myTestInstance2 = Object.create(myTest);

console.log("instance1.member2:"+myTestInstance1.member2);//Override
console.log("instance2.member2:"+myTestInstance2.member2);//m2

It’s also possible to change the prototype at any time in the life of the object and have every object changed. In the following example, two instances are created and the prototype is defined afterward. The data is still accessible by both instance after the assignation.

var myTest = {};
var myTestInstance1 = Object.create(myTest);
var myTestInstance2 = Object.create(myTest);
myTestInstance1.__proto__.member2 = "m2";

console.log("instance1.member2:"+myTestInstance1.member2);//m2
console.log("instance2.member2:"+myTestInstance2.member2);//m2

So far, the instance of the object was created by using create, but it’s also possible to do it with “new”.

var MyClass1 = function() {
  this.member1 = "m1";
};

MyClass1.prototype.function1 = function() {
  return "return from function1";
};

var instance1 = new MyClass1();

console.log("instance1.member1: "+ instance1.member1);//m1
console.log("instance1.function1: "+ instance1.function1());//return from function1

TypeScript Class Decorator : Method Performance

TypeScript supports decorator for classes, methods, properties, parameters and attributes. In this post, we will see how to create a decorator that will sit on top of a method. The goal of this decorator is to have an easy way to add to any of your method some code that will be executed. This is good for re-usability and doesn’t need you to have to add a call inside your method for every method you need to have something executed. We will see that we need to change TypeScript compiler, how to create the decorator and how to use this one.

The use of decorator is still very recent and it needs TypeScript to activate experimental decorator on. This is done by adding in the compilerOptions section of TypeScript compiler the “experimentalDecorators” to true. While many other decorator types require also to have “emitDecoratorMetadata” on, this is not the case with method.

{
  "compilerOptions": {
    "target": "es6",
    "experimentalDecorators": true
  }
}

The decorator for the method is one of the most powerful decorator. It is executed when the method is called which allow you to do something before and after this one. If you are from .Net, it’s a little bit like using a class that inherit IDisposable and have this one wrapping the whole method. The resemblance is that the Disposable method can do something in the constructor as a pre-execution code and do something in the dispose method as post-execution.

class MyCSharpClass{
    public void TestMethod(){
        using(new PseudoDecoratorButInsideMethod()){
        //Code here
        }
    }
}

In TypeScript, there is not something similar else than doing function function callback where you also wrap the code you want to decorate by executing a method that will do your pre and post code. The disadvantage is like with the .Net alternative which is that it needs intervention withing the method.

class MyClass{
    myMethod() {
        this.doSomething(() => {
            console.log("Inside")
        });
    }
    doSomething(callBack:Function):void {
        console.log("Before");
        callBack();
        console.log("After");
    }
}

The decorator version is more clean and doesn’t need you to change the method where you want to inject some logic.

class MyClass{
    @myMethodDecorator
    myMethod() {
       console.log("Inside")
    }
}

From here you should see some scenario where it makes sense to use decorator or not. I’ll illustrate one by using a method decorator to capture the time a method takes to execute. I’ll call this method “performanceLog” and will allow to supply two parameters, which the latest will be optional with a default value. The first parameter will tell if we want to display in the console the performance. The rational behind it that we may just want to log the information into our telemetry system in production. The second parameter is when to change the log into an error. It’s the threshold in millisecond of when it’s too long for the method.

To be able to have parameter, we must wrap the decorator into a function. Then, we need to return a function that has 3 parameters. The first one is the target which is the class prototype. This will allow us to dig inside the class to get into the method which is defined by the second parameter. Finally, the third parameter is a variable that contain the value of the method — this is where we will define the new method we want to swap from the original. As you saw in the previous way to do, we needed to have a callback that was executed between two statements. This is similar. We will extract the actual method and reuse this one between two statements and return a “new” methods into the value.

export function performanceLog(outputConsole: boolean, thresholdToDisplayErrorInMs: number = 1000) {
    /**
     * @params{any} target - The prototype of the class (Object).
     * @params{string} propertyKey - The name of the method.
     * @params{PropertyDescriptor} descriptor - Property that has a value (in that case the method)
     */
    return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
    }
}

To get the performance of a method, we need to collect the time before executing the original method, and display the final time, after its execution. So, first, before doing anything there is two important steps to do. We need to ensure that we have a descriptor defined (third parameter). This may be overridden by another decorator, hence we need to be sure it’s defined, if not to create back this one. Then, we need to do a copy of the original method because we want to execute it at the proper time.

export function performanceLog(outputConsole: boolean, thresholdToDisplayErrorInMs: number = 1000) {
    return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
        // Ensure we have the descriptor that might been overriden by another decorator
        if (descriptor === undefined) {
            descriptor = Object.getOwnPropertyDescriptor(target, propertyKey);
        }
        // Copy
        const originalMethod = descriptor.value;
        // To be continued
    };
}

Next, we need to create the new function that will be swapped from the original. This is done by defining a new function in the descriptor.value. You should not use the arrow function syntax because it will mess up the “this” pointer. To get more data for the log, you can get all parameters passed by stringify all parameters. After, you can start a timer and get the user time and call the original method. You must collect the result (in case of method that return something else than void) and stop the timer.

// Redefine the method to this new method who will call the original method
// Use the function's this context instead of the value of this when log is called (no arrow function)
descriptor.value = function (...args: any[]) {
  const parametersAsString = args.map((parameter) => JSON.stringify(parameter)).join(",");
  const startTime = window.performance.now();
  const result = originalMethod.apply(this, args); // Call the original method
  const endTime = window.performance.now();
  const timespan = endTime - startTime;
  const stringResult = JSON.stringify(result);
// To be continued
}     

The last step is to bring everything to live with showing in the console the performance by using the threshold. Here is the complete TypeScript decorator method.

export function performanceLog(outputConsole: boolean, thresholdToDisplayErrorInMs: number = 1000) {
    return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
        // Ensure we have the descriptor that might been overriden by another decorator
        if (descriptor === undefined) {
            descriptor = Object.getOwnPropertyDescriptor(target, propertyKey);
        }

        const originalMethod = descriptor.value;
        // Redefine the method to this new method who will call the original method
        // Use the function's this context instead of the value of this when log is called (no arrow function)
        descriptor.value = function (...args: any[]) {
            const parametersAsString = args.map((parameter) => JSON.stringify(parameter)).join(",");
            const startTime = window.performance.now();
            const result = originalMethod.apply(this, args); // Call the original method
            const endTime = window.performance.now();
            const timespan = endTime - startTime;
            const stringResult = JSON.stringify(result);
            if (outputConsole) {
                const message = "Call [" + timespan + "ms]: " + propertyKey + "(" + parametersAsString + ") => " + stringResult;
                if (timespan < thresholdToDisplayErrorInMs) {
                    console.log(message);
                } else {
                    console.error(message);
                }
            }
            return result;
        };

        return descriptor;
    };
}

TypeScript decorators are still in an early stage like if you were to use them with JavaScript. Decorator with method are a lot more straight forward than other decorator that require other library to extract meta-data for example. Decorators are getting more popular and start to be even cornerstone to some popular JavaScript framework like Angular 2 (and 4). Like every new shiny language feature, using at the proper time is the key of success.

JavaScript Object.create vs new

It’s possible to create instance in JavaScript by using Object.create or using new called constructor function.

The Object.create creates an instance of an object with the prototype passed has first parameter. If a second parameter is provided, it will be used for this object only. This second parameter must be of type DefinedProperty.

var MyClass1 = function() {
  this.member1 = "m1";
};

MyClass1.prototype.function1 = function() {
  return "return from function1";
};

var instance1 = new MyClass1();
var instance2 = Object.create(MyClass1.prototype, {
  "member2": {
    value: "m2",
    writable: true
  }});

console.log("instance1.member1: "+ instance1.member1);//m1
console.log("instance1.function1: "+ instance1.function1());//return from function1
console.log("instance2.member1: "+ instance2.member1);//undefined
console.log("instance2.member2: "+ instance2.member2);//m2
console.log("instance2.function1: "+ instance2.function1());//return from function1
console.log("instance1.member2: "+ instance1.member2);//undefined

This example show that the member “member1” is only present on the first instance because the second instance is created with just the prototype of MyClass1. It also shows that the instance 1 doesn’t have the member2 added by the second parameter of Object.create since it is a member added to the instance 2.

Object.create and constructor function both create a new object and bot set the __proto__ but in a different way. Object.create sets the __proto__ to be the one passed as the first parameter. The constructor function set the __proto__ to the type specified prototype (in the previous example MyClass1.prototype). The major difference is that Object.Create returns the new object while the constructor function return the constructor of the object or the object.

If we modified the preview code to have a console.log() in the constructor of the object, we can see that this one is executed only when using “new” and not when using Object.create.

var MyClass1 = function() {
  this.member1 = "m1";
  console.log("MyClass function");
};

MyClass1.prototype.function1 = function() {
  return "return from function1";
};

//var instance1 = new MyClass1();

var instance2 = Object.create(MyClass1.prototype);

The code above doesn’t execute the console.log. However, if we uncomment instance1 and comment instance2 (Object.create). We can see that it’s called.

In a future article, we will see that with Object.create that it’s possible to create inheritance.

How to setup your Kanban Board for your Dev team in 5 minutes

We are using VSTS at Microsoft Teams like many products at Microsoft. A few weeks ago, I decided to change our process of using the backlog as main view by using the Kanban board. As you may know, I worked for many years in VSTS and it feels so natural to have a quick glimpse of the Kanban board to know how everything is going. The reason is multiple but the main one is it was hard to figure out the state of each members. It was also hard to have a distinct view about what the front-end and the back-end team were working on. The last real benefit for me is that we do not need to waste time to evaluate every requirements and bugs, we just sort them in order of priority and blitz them through. In this post, I’ll give you a short way to build a Kanban Board that work for developers.

Starting with the Kanban board is not obvious. You need to go in your project, and click the “Work”, then “Backlog”. Then, you need to select the Backlog items on the left. There no indication of “Kanban” anywhere.

When you arrive there the first time, it’s even more disconcerting. You will see 4 columns which is “New”, “Approved”, “Commited” and “Done”. These are the default Kanban columns which doesn’t mean anything if you do not that flow which is almost all the time. So, we need to configure the columns. Configuring the Kanban board is done by clicking the gear at the top-right of the board.

This dialog contains many options and they are not ordered especially in the order to create a new board. What you want to do is skip all the Cards options which you should define later. Click “Columns” under “Board” and let’s change it into a flow that worked for me in the past as well as now. The first column to change is “Approved” for “Specs/Investigations”. This column will be the first step and used by your project manager or by your engineering manager to specify which work is getting details about them. This is also good for bug which will get there to be in investigation before having a coded fix. This column is also having the special option “Split column into doing and done”. This will result of having the column divided in two. The first part will be where someone commit working on it, and the other one is when the investigation or specification is written. This way, engineers knows that they can pick work from the column, not before. Having this column make it very clear when something is ready to pass to the next step and this is a must in teams that work fast and in an agile way. Anything in that column should be always pickup from top to bottom, whoever is available to grad new work.

The next columns are “Code”, “Tests”, “PullRequest”, “Verification” and we keep “Done”. The column code is when the developer is actually working on the code to build the requirement or fixing the bug. The column tests is when tests are created. Of course, unit tests can be written at the same time of your code, but this column ensure that additional integration code or even scenario tests are created. Sometime stuff doesn’t move there for a long time but it still good to see if something get stuck for a long time or not. The pull request columns means that the code is ready to be looked by others. Finally, when the pull request is in the master branch, you can move the work in the verification column which mean that it should be verified that everything work as intended in the master branch. Once verified, which can be done by people that are not even developer since it’s a verification that it works as intended. Once everything good, it goes in the Done.

Remember that bugs and requirement uses this board, so we must ensure that bug are manager with require the board to be setup this way. To change the behavior, in the board setting, go under “General” and “Working with bugs” and check “Bugs are managed with requirements”.

Next and last step is to separate the front-end and back-end work. This way, you can see what can block each others. This can be done by using the concept of swim lane. We will create one for the front and one for the back. This will divide the board in 2 vertically.

Of course, you can customize a lot more your board and VSTS is great to have coloring rules for example. However, within 5 minutes you can have your teams be up-and-running without doing too much.