What is a javascript prototype?

What is a prototype in javascript?

A prototype is an object. Every object in javascript has it as a property. It can be considered the template for that object, and any other objects will use it to  inherit properties.

When you want to dynamically add properties or methods to a javascript 'class', you will use the prototype:

function bank(balance)
   this.balance = new_balance;
   this.getBalance = function(){ return this.balance; }

bank.prototype.deposit = function(amount){ this.balance += amount; }

var my_account = new bank(0);
alert("New balance is " + my_account.getBalance(); }

So the object prototype is found in object.prototype?

Uh, no. Although you will use object.prototype to modify the object's prototype, it isn't technically found there. If you want to access the actual prototype object, you need to look elsewhere. The object.prototype property is the prototype that is assigned to all instances of the object,

The true prototype of an object is held in the internal [[Prototype]] property. ECMA 5 introduced a standard accessor Object.getPrototypeOf(object) which works in Firefox, Safari, Chrome and IE9. All browsers (except IE -- surprise!) support the non-standard accessor __proto__. Finally, we can reach it through the object’s constructor via the prototype property.

var a = {};

//Fails in Opera or IE<=8
var myPrototype = Object.getPrototypeOf(a); //returns [object Object]

//Fails in IE
var myPrototype = a.__proto__; //returns [object Object]

// works all browsers
//(but only if constructor.prototype has not been replaced and fails with Object.create)
var myPrototype = a.constructor.prototype; //returns [object Object]

Can any object be a prototype?

Hell, yes.

The $64,000 question: so what?

The prototype is the seed for all other objects.  It's a way to dynamically change the internals of any javascript 'class'. When you update the prototype, any previously instantiated objects gain the update.

var dog = { }

var my_dog = new dog();
alert(dog.name); // undefined

dog.prototype.name = 'sparky';
alert(my_dog.name); //'sparky';

dog.prototype.setName = function(name){ this.name = name; }
dog.prototyp.getName = function(){ return this.name; }

alert(my_dog.getName()): // 'fido';

No comments:

Post a Comment