All about Objects

Trying to sum up the essentials of objects in javascript as succinctly as possible but with enough examples to illustrate the concepts clearly.

I will add more and update this page as it occurs to me until I feel satisfied that its as complete and helpful as possible.

Creating Objects

// the traditional way using the Object constructor
var myObj = new Object();

//now add your properties and methods
myObj.str = "Hello";
myObj.num = 5;
myObj.arr = [1, 2, 3, 4, 5];
myObj.subObject = {title: "Psycho", year: "1960"};
myObj.fn = function() { alert( this.str ) };


//object literal
var myObj = {
	str: "Hello",
	num: 5,
	arr: [1, 2, 3, 4, 5],
	subObject: {title: "Psycho", year: "1960"},
	fn: function() { alert( this.str ) }
};


// Defining your own constructor function to create
// a custom object type
function CustomObj(str, num, arr, sub, fn) {
	this.str = str;
	this.num = num;
	this.arr = arr;
	this.subObject = sub;
	this.fn = fn;
}

// then create an instance of Obj withe the new keyword and 
// pass in your arguments
var myObj = new CustomObj("Hello", 5, [1,2,3], {name: "Joe"}, 
function() {alert(this.str)});

Diving deeper into the sea of Objects.

var Person = function (firstName) {
  this.firstName = firstName;
};

var Cat = function (n, s) {
  this.name = n;
  this.sex = s;
};

Person.prototype.sayHello = function() {
  console.log("Hello, I'm " + this.firstName);
};

var person1 = new Person("Alice");
var person2 = new Person("Bob");
var person3 = new Person("John");

person2.prototype = {objname : "person2 prototype"};

person3.prototype = new Cat("Fluffy", "female");

person1.sayHello(); // logs "Hello, I'm Alice"

person2.sayHello(); // logs "Hello, I'm Bob"

console.log(person1.firstName); // Alice

console.log(person1.prototype); // undefined

console.log(Person.prototype); // shows the object with its sayHello function

console.log(Object.getPrototypeOf(person1)); // same as above

console.log(Person); // shows the constructor function

console.log(Person.prototype.sayHello); // show the function

Person.prototype.sayHello(); // call the function

console.log(person1.constructor); // shows the constructor function

console.log(person2.prototype); // shows the object with its objname prop

console.log(Object.getPrototypeOf(person2));

console.log(person3.prototype); // shows the object with its two props

console.log(Object.getPrototypeOf(person3)); // the prototype object of person3 
is an instance of Person

prototype and Object.getPrototypeOf

JavaScript is a bit confusing for developers coming from Java or C++, as it’s all dynamic, all runtime, and it has no classes at all. It’s all just instances (objects). Even the “classes” we simulate are just a function object.

You probably already noticed that our function A has a special property called prototype. This special property works with the JavaScript new operator. The reference to the prototype object is copied to the internal [[Prototype]] property of the new instance. For example, when you do var a1 = new A(), JavaScript (after creating the object in memory and before running function A() with this defined to it) sets a1.[[Prototype]] = A.prototype. When you then access properties of the instance, JavaScript first checks whether they exist on that object directly, and if not, it looks in [[Prototype]]. This means that all the stuff you define in prototype is effectively shared by all instances, and you can even later change parts of prototype and have the changes appear in all existing instances, if you wanted to.

If, in the example above, you do var a1 = new A(); var a2 = new A(); then a1.doSomething would actually refer to Object.getPrototypeOf(a1).doSomething, which is the same as the A.prototype.doSomething you defined, i.e. Object.getPrototypeOf(a1).doSomething == Object.getPrototypeOf(a2).doSomething == A.prototype.doSomething.

In short, prototype is for types, while Object.getPrototypeOf() is the same for instances.

[[Prototype]] is looked at recursively, i.e. a1.doSomething, Object.getPrototypeOf(a1).doSomething, Object.getPrototypeOf(Object.getPrototypeOf(a1)).doSomething etc., until it’s found or Object.getPrototypeOf returns null.

So, when you call

var o = new Foo();

JavaScript actually just does

var o = new Object();
o.[[Prototype]] = Foo.prototype;
Foo.call(o);

(or something like that) and when you later do

o.someProp;

it checks whether o has a property someProp. If not it checks Object.getPrototypeOf(o).someProp and if that doesn’t exist it checks Object.getPrototypeOf(Object.getPrototypeOf(o)).someProp and so on.

/////////////////

 

 

////////////
var o = {a: 1, b: 2};

o.__proto__ === Object.prototype; // true
Object.getPrototypeOf(o) === Object.prototype; // true
Object.getPrototypeOf(o) === Array.prototype // false
o.hasOwnProperty(‘a’); // true
o.constructor // function Object()
o.hasOwnProperty(constructor) // false

o.__proto__.__proto__; // null

///////////////////

var o = {a: 1, b: 2};
var m = {c: 3, d: 4};
o.__proto__ = m;

o.__proto__ === m; // true

m.__proto__ === Object.prototype // true

o.__proto__ === Object.prototype // false

o.__proto__.__proto__ === Object.prototype // true

//////////////

var myfunc = function() {};

myfunc.name // “myfunc”

myfunc.length // 0

Function.prototype.constructor === Function // true

// Functions have a prototype property but objects don’t
// However both have actual [[Prototype]]s since both are objects

myfunc.constructor // function Function()

myfunc.hasOwnProperty(‘constructor’) // false

myfunc.__proto__.hasOwnProperty(‘constructor’) // true

///////////////////

function A () {
this.aprop = “a”;
}

function B () {
A.call(this)
this.bprop = “b”;
}

var myb = new B();

myb instanceof B; // true

myb instanceof A; // false

myb.aprop // a

myb.hasOwnProperty(‘aprop’); // true