Posts

Showing posts with the label Javascript

Difference between Object.create and new - Javascript

The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype. Object.create  builds an object that inherits directly from the one passed as its first argument. With constructor functions, the newly created object inherits from the constructor's prototype, e.g.: var o = new SomeConstructor (); In the above example,  o  inherits directly from  SomeConstructor.prototype . There's a difference here, with  Object.create  you can create an object that doesn't inherit from anything,  Object.create(null); , on the other hand, if you set  SomeConstructor.prototype = null;  the newly created object will inherit from  Object.prototype . You cannot create closures with the Object.create syntax as you would with the functional syntax. This is logical given the lexical (vs block) type scope of JavaScript. Well, you ...

How does javascript prototype works - Javascript

    In a language implementing classical inheritance like Java, C# or C++ you start by creating a class--a blueprint for your objects--and then you can create new objects from that class or you can extend the class, defining a new class that augments the original class. In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it. It's not difficult, but a little foreign and hard to metabolize for somebody used to the classical way. Example: //Define a functional object to hold persons in JavaScript var Person = function ( name ) { this . name = name ; }; //Add dynamically to the already defined object a new getter Person . prototype . getName = function () { return this . name ; }; //Create a new object of type Person var john = new Person ( "John" ); //Try the getter alert ( john . getName ()); //If now I...

CommonJS basics - Javascript

Ref: https://egghead.io/lessons/nodejs-commonjs-basics-introduction

Scope of variables - Javscript

A globally-scoped variable var a = 1 ; // global scope function one () { alert ( a ); } Local scope var a = 1 ; function two ( a ) { alert ( a ); } // local scope again function three () { var a = 3 ; alert ( a ); } Intermediate : No such thing as block scope in JavaScript (ES5; ES6 introduces let ) var a = 1 ; function four () { if ( true ) { var a = 4 ; } alert ( a ); // alerts '4', not the global value of '1' } Intermediate : Object properties var a = 1 ; function five () { this . a = 5 ; } Advanced : Closure var a = 1 ; var six = ( function () { var a = 6 ; return function () { // JavaScript "closure" means I have access to 'a' in here, // because it is defined in the function in which I was defined. alert ( a ); }; })(); Advanced : Prototype-based scope resolution var a = 1 ; function seven () { th...