Section 6 - Building Objects
typeof, instanceof, and Figuring out what Type it is
typeof specifies what we might expect: it return the type of a variable.
var a = 3;
console.log(typeof a); //number
var a = true;
console.log(typeof a); //boolean
var a = "string";
console.log(typeof a); //string
var a = {};
console.log(typeof a); //object
Arrays are also object types - but we cant further specify what type of object.
var a = [];
console.log(typeof a); //object
console.log(Object.prototype.toString.call(a)); //object array
Instance of looks down the prototype chain to see if an object is can be found inside of another object.
function Person(name) {
this.firstname = name;
}
var a = new Person('dan');
console.log(typeof a); //object
console.log(a instanceof Person); //true
As a review, new returns a newly constructed object whose 'this' return the object it was constructed under.
Important note: instanceof does not compare two objects. Rather, it looks at where the source came from. When we create any object, we also create an instance of an object, that comes from the constructor.
function Person2(name) {
this.firstname = name;
}
var b = new Person2('dan2');
console.log(a instanceof b); // expects and function, error
A few more
console.log(undefined); //undefined console.log(null); // object var a = function z() {}; console.log(a); // function
null returns an object. This is still considered to be a bug.
And a function returns a function object.
Strict Mode
Can help prevent error under some circumstances.
Your telling the js engine to use some extra, more strict rules when running your code.
include on the top of a file, or function.
Same rules of scope apply
//doesnt work, object needs to be initialized as a variable
function doSomething() {
"use strict";
person2 = {};
console.log(person2);
}
//works
person = {};
console.log(person);
doSomething();
A bit dangerous, because if it cannot find a variable, it looks up the scope chain.
More strict parser settings are applied.
Not all js engines agree on what 'strict' means. Not 100% reliable.
Varies by browser.
Last updated
Was this helpful?