JS Screen Objects, Prototypical Inheritance, Promises - Yash-777/SeleniumDriverAutomation GitHub Wiki

Screen Object: The screen object contains information about the visitor's screen.

Note: There is no public standard that applies to the screen object, but all major browsers support it.

Screen Object Properties:

Property Description
availHeight Returns the height of the screen (excluding the Windows Taskbar)
availWidth Returns the width of the screen (excluding the Windows Taskbar)
colorDepth Returns the bit depth of the color palette for displaying images
height Returns the total height of the screen
pixelDepth Returns the color resolution (in bits per pixel) of the screen
width Returns the total width of the screen

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.

The promise constructor takes one argument, a callback with two parameters, resolve and reject. Do something within the callback, perhaps async, then call resolve if everything worked, otherwise call reject. Like throw in plain old JavaScript, it's customary, but not required, to reject with an Error object.

var promise = new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…

  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

then() takes two arguments, a callback for a success case, and another for the failure case. Both are optional, so you can add a callback for the success or failure case only.

promise.then(
             function(result) {
                console.log(result); // "Stuff worked!"
             },
             function(err) {
                console.log(err); // Error: "It broke"
             }
            )
       .catch(
               function (message) {
                 console.log( error message );
               }
             );

There are already implementations of promises in browsers today.
As of Chrome 32, Opera 19, Firefox 29, Safari 8 & Microsoft Edge, promises are enabled by default.

A promise can be:

  • fulfilled - The action relating to the promise succeeded
  • rejected - The action relating to the promise failed
  • pending - Hasn't fulfilled or rejected yet
  • settled - Has fulfilled or rejected

Singel Promise «

let myFirstPromise = new Promise(function (resolve, reject) {
    // We call resolve(...) when what we were doing async succeeded, and reject(...) when it failed.
    // In this example, we use setTimeout(...) to simulate async code.
    // In reality, you will probably be using something like XHR or an HTML5 API.
    setTimeout(function () {
        console.log('async call');
        let isValid = false;
        if (isValid) {
            resolve('Valid');
        } else {
            reject('not Valid');
        }
        resolve("Success!"); // Yay! Everything went well!
    }, 2500);
});

myFirstPromise.then(function (message) {
        // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
        console.log('the user is ', message, ' « So he can login and perform actions');
        console.log("Yay! " + message);
    })
    .catch(function (message) {
        console.log('the user is ', message, ' « So he has to signup');
    })

Javascript Beautifiers « {http://jsbeautifier.org/, http://codebeautify.org/jsviewer, http://www.danstools.com/javascript-beautify/}

Multiple Promises « Promises depends on other promises « [ Ex: NodeJS - Selenium WebdriverJS ]

let loadApplicationURL = new Promise(function (resolve, reject) {

    // Wait for Web Application to Load.
    let isLoaded = true;
    if (isLoaded) {
        resolve('Loaded');
    } else {
        reject('not Loaded');
    }
});

let getTitle = function () {
    return new Promise(function (resolve, reject) {
        resolve('Application Title : ' + document.title);
    });
}

function wait(ms) {
    var start = new Date().getTime();
    var end = start;
    while (end < start + ms) {
        end = new Date().getTime();
    }
}

let getElement = function () {
    return new Promise(function (resolve, reject) {
        var element = document.getElementsByTagName('input')[0];
        if (element != 'undefined') {
            console.log('Element found Ele : ', element);

            resolve(element);
        } else {
            console.log('Element not found ');
            reject('Element not found');
        }
    });
}
let setElementBGColor = function (element) {
    return new Promise(function (resolve, reject) {
        console.log('Element style with background color Red');
        element.style.backgroundColor = 'red';
        resolve(element);
    });
}
let sendKeysToEle = function (element) {
    return new Promise(function (resolve, reject) {
        console.log('before');
        wait(7000); //7 seconds in milliseconds
        console.log('after');

        console.log('Element inserted with innerHTML data');
        element.innerHTML = "Search Key";
        resolve();
    });
}

// Call Promises
loadApplicationURL.then(function(fromResolve) {
    console.log('Applciation ' + fromResolve);
    // independent Single Fun
    getTitle().then(function(response) {
        console.log('Promise Return MSG : ', response);
    })

    // Dependent functions : One function depends on the response of its super | parent function.
    getElement()
        .then(function(element) {
            return setElementBGColor(element);
        })
        .then(function(element) {
            return sendKeysToEle(element);
        })
        .then(function() {
            console.log("Completed Promise.");
        })

}).catch(function(fromReject) {
    console.log('Application ' + fromReject);
})

Every JavaScript object has an internal property called [[Prototype]].

  • object creation «
  • JSON « Object {Key : Value}
var jsonObj = { key : 'val' }
console.log( jsonObj );
/* OUTPUT:
	« Object {key: "val"}
		key:"val"
		__proto__:Object
*/
  • Object.create(null) « Object {}No Properties
var nullCreateObj = Object.create(null);
console.log( nullCreateObj );
/* OUTPUT:
	« Object {}
		No Properties
*/
  • Object.create({}); « Object {}proto: Object
var jsonCreateObj = Object.create({});
console.log( jsonCreateObj );
/* OUTPUT: JOSN,CREATE
	« Object {}
		__proto__: Object
			__proto__: Object
*/
  • Object.create({}); « Object {}proto: Object
function myFinction(name){  this.name = name;  }
var functionCreateObj = Object.create( myFinction );
console.log( functionCreateObj );
/* OUTPUT:
	« Function {}
		__proto__: myFinction(name)
*/
  • object property value «
  • You can check your property value using obj.hasOwnProperty('propName') - the run time looks up the property in the object referenced by [[Prototype]] instead
var globalKey;

function person(name) {
    this.name = name;
}
var accessFunctions = {
  getName: function(){ return this.name; },
  setName: function( name ){ this.name = name; },
  getDOB: function(){ return this.dob; },
  setDOB: function( dob ){ this.dob = dob; },

  setKey: function( key ){ globalKey = key; },
  getKey: function(){ return globalKey; },

  setProduct: function( pname ){ this.pname = pname ; },
  getProduct: function(){ return pname; },
  setAmount: function( amount ){ this.amount = amount; },
  getAmount: function(){ return amount; },
};

person.prototype.getName = accessFunctions['getName'];
person.prototype.setName = accessFunctions['setName'];
person.prototype.setDOB = accessFunctions['setDOB'];
person.prototype.getDOB = accessFunctions['getDOB'];
person.prototype.setKey = accessFunctions['setKey'];
person.prototype.getKey = accessFunctions['getKey'];

for (var key in accessFunctions) {
    // newObject[key] = accessFunctions[key];
    console.log(key + " : " + accessFunctions[key]);
}

//Create a new object of type Person
var pName = new person("Yash");
pName.setKey('Global Key');
pName.setDOB('AUG');
console.log(pName);

var pName2 = new person();
pName2.setName("Sam");
console.log(pName2);
console.log(pName2.getKey());

var product = function (name) {
    this.name = name;
};
product.prototype = pName;
//product.prototype = new person("SAM");
product.prototype.setProduct = accessFunctions['setProduct'];
product.prototype.getProduct = accessFunctions['getProduct'];
product.prototype.setAmount = accessFunctions['setAmount'];
product.prototype.getAmount = accessFunctions['getAmount'];

var myProduct = Object.create(new product('Phone'));
console.log("myProduct:");
console.log(myProduct);

myProduct.setName("Yash_777");
//myProduct.setProduct("Iphone");
myProduct.setAmount("$600");
myProduct.setDOB("AUG");
console.log(myProduct);
console.log(myProduct.getKey());

Image Data

  • Left var myProduct = new product('Phone');

  • Right var myProduct = Object.create(new product('Phone')); Prototypical Inheritance

  • prototype chain « JavaScript doesn't have inheritance in the usual sense, but it has the prototype chain. The advantage of adding a function / variable to the prototype is that it has to be in the memory only once, not for every instance. prototype chain ultimately falls back to Object.prototype.

Object Memory Allocation only once

⚠️ **GitHub.com Fallback** ⚠️