Skip to main content

Posts

Showing posts with the label javascript

`this` keyword in javascript

this keyword used to reference current object in javascript. There are two scenario where current object is determined differently. * Calling object represented by `this` in function. * Arrow function can reference object where the function defined. To demonstrate the above scenarios we shall take some examples. Suppose, var x = 10; (function() {    console.log(this.x); })() // 10 (() => {    console.log(this.x); })() // 10 There are two self executing functions both resulted in "10". At first look it seems behaving same, but there is basic deference what we going to see. const xObj = {     value: 10,     getValue: () => {         return this.value;     } }; const yObj = {     value: 10,     getValue: function () {         return this.value;     } }; xObj.getValue(); // undefined yObj.getValue(); // 10 Why undefined for `xO...

Inheritance with constructor function in javascript

Object literal like var derived = {     a: 10 }; be easily extended using derived.__proto__ = base; where base is var base = {     x : 5 }; But, what if we using constructor function? We need to do like this var Person = function (name) {     this.name = name; } Person.prototype.sayHello = function () {     console.log('Hello, I am '+this.name); } Person.prototype.getName = function () {     return this.name; } var per = new Person('Manan'); per.sayHello(); //prints --> Hello, I am Manan var Employee = function (name, company) {     Person.call(this, name);     this.company = company; } Employee.prototype.sayHello = function () {     console.log('Hello, I am '+this.getName()+' and I am working at '+this.company); } Employee.prototype.__proto__ = Person.prototype; var emp = new Employee('Manan', 'Integ'); emp.sayHello(); //prints --> Hello, I am Manan and I am workin...

Javascript function and object structure

Javascript has function and object structure. We tries to understand this. Function is an object and an object is created by some function. When a function creates an object, the function assign its prototype value to __proto__ property of newly created object. Object.prototype  is the last object in prototype chain. It is base object for all functions and objects. Javascript has pattern that __proto__ of function would be type of function and __proto__ of object would be type of object. This is also true for Number, Array etc. Lets check diagram of javascript function and object structure. (We shall call in-built unnamed function as System function .) If we create obj using object literal, var obj = { a: 0 }; The obj is created by Object . Here, the Object function is used implicitly as creator function. obj.__proto__ === Object.prototype   // true If we create an instance using creator function. var foo = new Foo(); ...