Obj3ctiv3_C_88
Obj3ctiv3_C_88

Reputation: 1528

Details on prototypes

So I'm coming from Python and trying to wrap my head around what a prototype is. Is there anyway I could get a Pythonic description of a Prototype? It kind of sounds like a descriptor had a baby with init. Also, I heard that Prototype tends to have negative consequences when being used on the DOM. Is that true? If so, why? Thanks, I've been looking through a ton of articles and the Prototype just isn't making sense to me at this point!

Upvotes: 1

Views: 49

Answers (1)

Luke
Luke

Reputation: 5708

In Javascript, much like Python, everything is an object. This includes functions.

Javascript doesn't have classes though. However, you can use functions to simulate the behavior of classes.


All functions have a property called prototype. If you say:

myInstance = new myFunction()

myFunction is run. (So it acts like a constructor) and the result is stored in myInstance. Nothing crazy here, but what that new keyword does is copy the prototype property from myFunction over to an internal property of myInstance. This property is referred to in the docs as [[prototype]] and you can reference it in some modern browsers as __proto__. __proto__ is not standardized though, so its use is discouraged.

If you need to get the [[prototype]] of an object, rather than using __proto__ use Object.getProtoTypeOf(myInstance).

MyClass.prototype == Object.getPrototypeOf(myInstance) //true

When you call a method on an object, if the object doesn't have that method, Javascript will look in its [[prototype]] property. It will keep searching the prototype (a.k.a. inheritance) chain until it reaches Object.

So as an example:

function MyClass() {
  this.prop ="hello"

  //Javascript implicitly returns `this` when the function is invoked using "new"
} 

MyClass.prototype.instanceMethodOne = function() {
  console.log(this.prop);
}

var myInstance = new MyClass();

myInsance.instanceMethodOne(); //"hello"

In the above example, myInstance will have a property called prop. But it will have no property called instanceMethodOne. This property was added to MyClass's prototype object. However, a reference to this object was copied to that [[prototype]] (a.k.a) __proto__ property of myInstance, so it is accessible.

You now have a situation where all instances have their own state, which is created in the constructor function (just a normal function) but they share the state that was added to the function's prototype property. This is how you get "classes" in Javascript.

Upvotes: 1

Related Questions