Monday, October 13, 2014

Creating Shorthand/Literal Values from Constructors

JavaScript provides shortcuts—called “literals”—for manufacturing most of the native object values without having to use new Foo() or new Bar(). For the most part, the literal syntax accomplishes the same thing as using the new operator. The exceptions are: Number(), String(), and Boolean()

var myRegExp = new RegExp('\bt[a-z]+\b');
var myRegExpLiteral = /\bt[a-z]+\b/;

var myObject = new Object();
var myObjectLiteral = {};

var myArray = new Array('foo', 'bar');
var myArrayLiteral = ['foo', 'bar'];

var myFunction = new Function("x", "y", "return x*y");
var myFunctionLiteral = function(x, y) {return x*y};

var myFunction = new Function();
var myFunctionL = function() {}; // literal shorthand

var myObject = new Object();
var myObjectL = {}; // literal shorthand
var myArray = new Array();
var myArrayL = []; // literal shorthand

var myNumber = new Number(23); // an object
var myNumberLiteral = 23; // primitive number value, not an object

var myString = new String('male'); // an object
var myStringLiteral = 'male'; // primitive string value, not an object

var myBoolean = new Boolean(false); // an object
var myBooleanLiteral = false; // primitive boolean value, not an object
var CustomConstructor = function CustomConstructor(){ return 'Wow!'; };
var instanceOfCustomObject = new CustomConstructor();
// logs true
console.log(instanceOfCustomObject.constructor === CustomConstructor);
// returns a reference to CustomConstructor() function
// returns 'function() { return 'Wow!'; };'
console.log(instanceOfCustomObject.constructor);

using literals simply conceals the underlying process identical to using the new operator. Maybe more importantly, it’s a lot more convenient!

JavaScript Enlightenment :
When using literal values for string, number, and boolean, an actual complex object is never created until the value is treated as an object. In other words, you are dealing with a primitive datatype until you attempt to use methods or retrieve properties associated with the constructor (e.g., var charactersInFoo = 'foo'.length). When this happens, JavaScript creates a wrapper object for the literal value behind the scenes, allowing the value to be treated as an object. Then, after the method is called, JavaScript discards the wrapper object and the value returns to a literal type. This is why string, number, and boolean are considered primitive (or simple) datatypes. I hope this clarifies the misconception that “everything in JavaScript is an object” with the concept that “everything in JavaScript can act like an object.”

When a primitive value is used as if it were an object created by a constructor, JavaScript converts it to an object in order to respond to the expression at hand, but then discards the object qualities and changes it back to a primitive value.

// Produce primitive values
var myNull = null;
var myUndefined = undefined;
var primitiveString1 = "foo";
var primitiveString2 = String('foo');//did not use new, so we get primitive
var primitiveNumber1 = 10;
var primitiveNumber2 = Number('10');//did not use new, so we get primitive
var primitiveBoolean1 = true;
var primitiveBoolean2 = Boolean('true');//did not use new, so we get primitive
/* Access the toString() property method (inherited by objects from
object.prototype) to demonstrate that the primitive values are converted to
objects when treated like objects. */
// logs "string string"
console.log(primitiveString1.toString(), primitiveString2.toString());
// logs "number number"
console.log(primitiveNumber1.toString(), primitiveNumber2.toString());
// logs "boolean boolean"
console.log(primitiveBoolean1.toString(), primitiveBoolean2.toString());
/* This will throw an error and not show up in firebug lite, as null and
undefined do not convert to objects and do not have constructors. */
console.log(myNull.toString());
console.log(myUndefined.toString());


Math is a static object—a container for other methods—and is not a constructor that uses the new operator

It’s possible to forgo the use of the new keyword and the concept of a constructor function by explicitly having the function return an object. The function would have to be written explicitly to build an Object() object and return it:
var myFunction = function(){
return {prop: val}
};
Doing this, however, sidesteps prototypal inheritance.

No comments:

Post a Comment