JavaScript Prototype

DONG Yuxuan

Every object in JavaScript is connected to a prototype. The prototype can be retrieved by the __proto__ attribute of the object. After an attempt to retrieve the value of an attribute is made, JavaScript firstly searches the object. If it has the attribute the value is returned. Else, JavaScript searches the prototype for the attribute. If the attribute is not in the prototype, it searches the prototype of the prototype, and so on, util it finds the attribute or the prototype becomes null.

We could iterate every attribute of an object and its prototype chain with the for in clause. To check whether an attribute is owned by the object itself we could use obj.hasOwnProperty(attr_name).

A function is also an object and it’s connected to Function.prototype. To be more specific, the following expression is true.

new Function().__proto__ === Function.prototype

A function can be used as a constructor to create an object by calling it with new. When the function is called as a constructor, this in the function body will be binded to the object it constructs and the constructed object is returned unless you explicitly return another instance of Object.

function Book(name, author) {
	this.name = name;
	this.author = author;
}

var jsbook = new Book('A JS Tutorial', 'Web Hackers');

// A JS Tutorial by Web Hackers
console.log(jsbook.name, 'by', jsbook.author);

Every function has an attribute named prototype. It’s notable that prototype is not the prototype of the function. As mentioned below, the prototype of the function can be retrieved by its __proto__ attribute. The prototype attribute will be used as the prototype of the object constructed by the function.

function Book(name, author) {
	this.name = name;
	this.author = author;
}

Book.prototype.printDescription = function() {
	console.log(this.author, 'wrote', this.name);
}

var jsbook = new Book('A JS Tutorial', 'Web Hackers');

// Web Hackers wrote A JS Tutorial
jsbook.printDescription();

// true
console.log(jsbook.__proto__ === Book.prototype);

The prototype attribute of a function has a special attribute constructor which points back to the function.

// true
console.log(jsbook.__proto__.constructor === Book);